#Basic Pycord Help (Quick Questions Only)

1 messages · Page 23 of 1

jovial dagger
#

I should go to sleep

spice oyster
#

Hello! What do I do when getting discord.errors.NotFound when doing something like await context.send_response(file = file) in a Slash Command? Sometimes it works, sometimes it doesn't. I wonder if it's just something about Discord servers.

spice oyster
# young bone what?
Traceback (most recent call last):
  File "C:\Users\Elitesparkle\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Elitesparkle\Documents\GitHub\Snowball\cogs\error.py", line 31, in on_application_command_error
    await context.respond(content = content, ephemeral = True)
  File "C:\Users\Elitesparkle\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\context.py", line 275, in respond
    return await self.interaction.response.send_message(*args, **kwargs)  # self.response
  File "C:\Users\Elitesparkle\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 727, in 
send_message
    await self._locked_response(
  File "C:\Users\Elitesparkle\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 975, in 
_locked_response
    await coro
  File "C:\Users\Elitesparkle\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
young bone
#

context.respond()?

#

why not ctx.respond()?

spice oyster
#

Eh, it's the same. I like it this way.

young bone
#

k

spice oyster
#

I guess I'm just being too slow at answering the interaction. rooThink

#

How can I randomly choose a .png file in a folder without taking too much time?

rugged lantern
#

why would a random choice be performance intensive

young bone
spice oyster
rugged lantern
#

defer?

spice oyster
#

I'll try, just to see what happens.

spice oyster
#

I did images = [file for file in files if file.endswith("png")] without defer and it's working (not always).

#

The weird part is that it worked fine for months, without changes, until today. Maybe the network is being slower somewhere today.

#

Ok, it's still happening. Could it be a server problem when uploading a big image? The biggest one is 4.61 MB and the smallest one is 1.02 MB.

#

I need to defer because images bigger than 3 MB take too much to be uploaded. Now it's working. Thanks for the help!

young bone
#

do you use it in a cog?

#

just use message

full basin
#

The on message event takes no context

#

Read the documentation.

young bone
#

on_message(message)....

proud pagoda
#

Is there any reason why my slash commands aren't reloaded when I restart my bot? On the prod version of the bot, I changed the name of one of the commands and have restarted the bot a few times since then, and the command name hasn't been updated yet, however on the dev version it got updated instantly. Ping on reply please

rare ice
proud pagoda
#

But it's been more than an hr

#

And anyway didn't Discord make it so that it refreshes instantly for global commands?

#

Well actually the slash cmd is part of a cmd group that's guild specific in both

silver moat
proud pagoda
#

how?

silver moat
#

comment, run, uncomment run

proud pagoda
#

Ok thanks

#

Yeah that worked, thanks for your help

coral kindle
#

How can I make my button work after bot restart

naive steppe
#

assign the button a custom_id
and add it to the on_ready

#

also the timeout must be set to none

granite crypt
#

Can pycord create forum posts?

granite crypt
fervent cradle
#

Is there a way to add permission to application commands(Context Menus)?

spice oyster
#

Hello! Is there a way to disable auto-generated imports in Visual Studio Code? They are kinda sneaky. notlikeduck

fervent cradle
#

I am trying to use modals but when I try to send a modal I get this error: Command raised an exception: AttributeError: 'BridgeExtContext' object has no attribute 'send_modal'. On the guide it shows that it's ApplicationContext instead of BridgeExtContext. I'm using a bridge command, how do I send a modal?

sinful pivot
#

I have a select menu, and I want to get which one they user has picked. I know it's like interaction.something[0]

#

just can't get it

fervent cradle
sinful pivot
#

got it, ty.

silver moat
spice oyster
fervent cradle
silver moat
sinful pivot
#

yea

#

u cant just go around randomly sending people modals when they did nothing

fervent cradle
#

so can i just use ctx.interaction.send_modal?

#

i'll try rn

sinful pivot
#

lol, if this was allowed then bots could be made that just loop through all of the members and send them all a modal and over and over

silver moat
fervent cradle
sinful pivot
#

can be only done with slash commands I think, not for bridgecommands

sinful pivot
fervent cradle
silver moat
sinful pivot
#

I seem to be getting discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'MyView' object has no attribute 'children'

#
class MyView(discord.ui.View):
    def __init__(self):
        self.votes: dict[str, int] = {}
    
    @discord.ui.select( 
        placeholder = "Choose a Flavor!", 
        min_values = 1, 
        max_values = 1,
        options = [
            discord.SelectOption(
                label="Vanilla",
                description="Pick this if you like vanilla!"
            ),
            discord.SelectOption(
                label="Chocolate",
                description="Pick this if you like chocolate!"
            ),
            discord.SelectOption(
                label="Strawberry",
                description="Pick this if you like strawberry!"
            )
        ]
    )
    async def select_callback(self, select, interaction):
        print(select.values[0])
#

legit just copied it from the guide website lol

#

its a poll view..

sinful pivot
#
    children = sorted(self.children, key=key)
AttributeError: 'MyView' object has no attribute 'children'```
#

discord wont let me send the whole thing

#
  File "C:\Users\HP\.virtualenvs\Test-u7DUJAa6\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\HP\.virtualenvs\Test-u7DUJAa6\lib\site-packages\discord\commands\core.py", line 359, in invoke
    await injected(ctx)
  File "C:\Users\HP\.virtualenvs\Test-u7DUJAa6\lib\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'MyView' object has no attribute 'children'```
#

there u go

fervent cradle
#

what are you trying to get by using children?

sinful pivot
fervent cradle
sinful pivot
#

I just have a TextChannel option and send the view to that channel.

sinful pivot
silver moat
sinful pivot
#

I'm using py-cord==2.1.3

silver moat
#

make an issue on github

sinful pivot
#

should I downgrade to 2.1?

sinful pivot
#

What should be the title?

#

I've never made a issue like this lol

silver moat
fervent cradle
#

Well apparently the prefixes commands aren't working at all

full basin
#

Do you have a setup function

fervent cradle
#

Yes

cyan quail
fervent cradle
#

Slash command works, hut prefix is not

cyan quail
#

they didn't super their custom class

fervent cradle
#

But

silver moat
obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

silver moat
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

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)
Discord Developer Portal

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

fervent cradle
#

Oh that is why

#

I guess ty

gilded niche
#

Is it possible to put a cooldown on a command only when the if function is true?

cyan quail
#

maybe i should write the example for it

iron halo
#

i added await ctx.defer() to make my bot stop saying unknown interaction but it says it even when i use that

#

is my bot just being slow

#

it only says it rarely

sweet quiver
#

Hello all
I checked in the previous threads and in doc, and I'm not sure what I want to achieve is doable:

I'd like to know who is executing a slash command during the typing phase
ex: in autocomplete, you can use ctx.options["option_name"] to get option_namevalue
But can I know who is the user who's typing ?

The goal, in fine, is to display a specific autocomplete list depending on the user's name

cyan quail
#

you can get pretty creative with autocomplete, e.g. as you said if you know who's using the command you can display custom information

#

in my case i built an inventory system with it

sweet quiver
#

Sadly, when I do this, I get an AttributeError: 'AutocompleteContext' object has no attribute 'author'

cyan quail
#

ah my mistake

#

ctx.interaction.user is what you're looking for

sweet quiver
#

Oh yes, indeed, it works. I'm gonna try to implement that 🙂

sage galleon
#
    await ctx.interaction.followup.send("Timed out.", ephemeral=True)
  File "/home/mrmetacom/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1561, in send
    data = await adapter.execute_webhook(
  File "/home/mrmetacom/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 213, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token

Anyone have any idea what this means? Can I not send ephemeral messages to certain people?

cyan quail
sage galleon
sage galleon
# cyan quail that's the whole command?

There's a shit ton of code that I'd rather not overwhelm you with lmao. This is a function that takes a list of items, turns them into buttons, then returns the selected button/item.

cyan quail
#

im assuming you responded somewhere before this then

#

and i guess defer

#

though on that note hm

sage galleon
#

Yes it works usually I just noticed this in the console when I logged into the server and am confused on why it happened.

cyan quail
#

did it take longer than 15 minutes?

sage galleon
#

I don't know like I said I didn't make it error the bot is in many servers

#

I just noticed it and am wondering how to prevent it from happening again 😛

cyan quail
#

GuraShrug i'd ignore it then, but you did say it takes a long time

#

interaction tokens last 15 minutes at max, so if it's beyond that you'll have to deal with it somehow

clever lake
#

How do you check if there is a video or image in an embed. I was trying if embed.video != discord.Embed.Empty or embed.image != discord.Embed.Empty but embed.video is returning EmbedProxy() and so is true

sage galleon
#

Or what it even means. My guess was the command timed out but wouldn't it execute that message being sent since it runs when timed_out is True?

cyan quail
#

if it goes beyond 15 mins then the followup won't work anymore

#

so you'd have to use another message sending method

cyan quail
sage galleon
cyan quail
#

ctx.interaction will always exist

#

you could probably get away with ctx.channel.send

#

maybe include a mention or something though

sage galleon
#

True I'm not super worried about telling the user the command timed out though especially if it's going to send another permanent message and add bloat. Just wondering if I can check for the timeout even though timed_out is supposed to literally be whether or not it timed out lmfao

vapid pumice
#

Did you figure this out? I'm getting the same error

sage galleon
#

I guess I could just try except pass it

#

Although I don't like adding those to my code

cyan quail
#

the issue is that you're using followup.send after the token's expired

sage galleon
#

Right but

timed_out = await view.wait()
if timed_out:
    view.disable_all_items()
    view.stop()
    await ctx.interaction.followup.send("Timed out.", ephemeral=True)

is what I'm referring to. The variable timed_out shouldn't be True if it has timed out and therefore the message shouldn't be attempted to be sent right?

cyan quail
#

wrong way

clever lake
fervent cradle
#

anybody?

clever lake
#

ok it works kinda. It still returns true if there is no video or image tho

vapid pumice
clever lake
cyan quail
clever lake
#

ah ok ur logic was correct but its cause i was being a dumbass and reversing the logic for what i needed

cyan quail
#

fun times

clever lake
#

im v sorry but ty for the sanity check

cyan quail
#

allgood

clever lake
#

i am a bit dumb sometimes xD

clever lake
#

I was trying to use on_message to get a message and then check if its embeds included a twitter link. Ive run into a bug tho where discord will hang when adding the embed to the twitter link but only the first time its sent. This results in there is no objects in the embed list.

Do you know if there is a good way to deal with this or should i change my approach to check if the link includes a url

#

the other approach is worse as it means i have to check if the twitter post is a video or not though

stiff flame
#

I'm new to env's so It might be a stupid mistake. But pyton can't find the module. It did work fine with discord.py (until I found out the owner quit and switched to pycord)

obtuse juncoBOT
#
  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

stiff flame
#

Well that did it, thnx

spice oyster
stiff flame
#

Oh really, well I'm switching back because this isn't working with pycord

spice oyster
rare ice
#

@stiff flame Run pip freeze

stiff flame
#

I'm sure pycord ain't bad, or that discord.py is better. I just have to go with one and stick with it

fervent cradle
#

Well I am back again with the same problem (Where prefixes command do not work) but this time I added intents and still does not work

rare ice
fervent cradle
#

I guess that is the problem, I am confused with the guide

cold jetty
#

how to disable command usage in dms

cobalt tangle
#
    @moderation.command(description="Unlock a channel")
    @discord.default_permissions(
    manage_channels=True,
    )
#

why doesnt this work, no error, but everyone in the server can use the cmd

#

even ppl without the perm

young bone
#

You also should use commands.has_permission()

cobalt tangle
#

this is slash cmd

#

discord.Bot()

young bone
#

Yes

cobalt tangle
#

it works just fine with my alt

#

even with @commands.has_permission()

young bone
#

What is your py-cord Version?

cobalt tangle
young bone
#

That is?

cobalt tangle
#

one sec

#

2.1.3

young bone
#

Can you try commands.Bot?

cobalt tangle
#

from .command to .slash_command

#

anyways i doubt that would make any difference

young bone
#

No

#

You can use slash commands with commands.Bot

cobalt tangle
#

ik

young bone
#

You have to change nothing

cobalt tangle
#

I have to change my whole code from @moderation.command to @moderation.slash_command

young bone
#

You still have to change nothing

cobalt tangle
#

...

#

ill test it

#

and this potentially may be a bug

young bone
#

Only discord.Bot to commands.Bot

rigid sable
#

This is my persistent view and it only sends out the second button labeled "Delete." Can you guys help me find out the error?

class PersistentView3(View):
  def __init__(self):
    super().__init__(timeout=None)

  @discord.ui.button(label="Re-open!",custom_id="rwqwerwerwerwer")
  async def button_callback(self, button, interaction):
    print("Hi")    
  @discord.ui.button(label="Delete!",custom_id="ewrwerewrwerwe")
  async def button_callback(self, button, interaction):
    print("Hi")    
#

Ping me if you guys know

spice oyster
graceful mason
#

Can I wait for callback?
for example

for i in range(5):
  button, interaction = view.wait_for_callback()
  i++
fervent cradle
#

Well off topic for codes but how do I start a new line in terminal like this?

fervent cradle
tiny wagon
#

then try && rather pressing enter

fervent cradle
tiny wagon
fervent cradle
#

Still cant btw

graceful mason
#

and enter

#

at least on linux

fringe socket
#

anybody want to help me in #1022887797629136926 ?

sharp smelt
#

What's the fastest way to ping the command sender?

fringe socket
#
await ctx.respond(f"{discord.Message.author.mention}")
cyan quail
#

...ctx.author.mention, that won't work

fringe socket
#

it works for me...

cyan quail
#

discord.Message is a generic message object, it won't have an author

fringe socket
#

How would I make a bot remove a certain reaction after a certain amount of time

rugged lantern
#

use remove_reaction instead of add_reaction after said time?

lost lodge
#

What does that error mean?

Traceback (most recent call last):
  File "/unviewed/discord/main/main.py", line 173, in <module>
    bot.run(config["token"])
  File "/unviewed/discord/main/venv/lib/python3.10/site-packages/discord/client.py", line 702, in run
    future = asyncio.ensure_future(runner(), loop=loop)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py", line 615, in ensure_future
    return _ensure_future(coro_or_future, loop=loop)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py", line 636, in _ensure_future
    return loop.create_task(coro_or_future)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 436, in create_task
    self._check_closed()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
fringe socket
rugged lantern
lost lodge
lost lodge
#

Help pls

fallen cove
#

Is there a way to check which guild a button interaction is made?

fallen cove
buoyant mesa
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction how do i solve this error

fervent cradle
#
@owners.command(name="manualnotify", description="Notify all users in a server.")
    async def send_manual_notification(self, ctx, circular_name: str, url: str,
                     category: discord.Option(choices=[
                         discord.OptionChoice("General", value=my_dict[str(ctx.author.id)]),
                     ])
    ):

Look at the first optionchoice, can i put custom options based on which user is using it

like getting them from a dict based on whos typing the cmd

is this possible?

lost lodge
young bone
fervent cradle
young bone
#

no

fervent cradle
#

kk

lost lodge
fervent cradle
young bone
rugged lantern
#

im pretty sure it is possible to make options based on what user is doing the command

fervent cradle
#

well what's config ?

lost lodge
young bone
lost lodge
rugged lantern
#

did i make that claim

lost lodge
#

?

full basin
obtuse juncoBOT
lost lodge
errant craneBOT
lost lodge
errant craneBOT
fervent cradle
fervent cradle
# fervent cradle please tell me how

for example you can compare the message author id to owner id

choices = []
if ctx.author.id == owner.id:
  choices=[discord.SelectOptionChoice("Owner")
else:
  choices=[discord.SelectOptionChoice("Not owner")

@owners.command()
async def send_notif(self, ctx, category: discord.Option(choices=choices)):
``` like this maybe
white wadi
#

when i shutdown the bot with exit() function or with CTRL+C i get an error, is it possible to get rid of that?

  _cancel_tasks(loop)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Task exception was never retrieved
future: <Task finished name='discord-ui-view-dispatch-b46dd376a01651123dbdc289008eec52' coro=<View._scheduled_task() done, defined at /usr/local/lib/python3.9/dist-packages/discord/ui/view.py:366> exception=SystemExit(None)>
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/discord/client.py", line 705, in run
    loop.run_forever()
  File "/usr/lib/python3.9/asyncio/base_events.py", line 596, in run_forever
    self._run_once()
  File "/usr/lib/python3.9/asyncio/base_events.py", line 1890, in _run_once
    handle._run()
  File "/usr/lib/python3.9/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.9/dist-packages/discord/ui/view.py", line 375, in _scheduled_task
    await item.callback(interaction)
  File "/opt/pbot-source-code/main.py", line 245, in regen_button_callback
    exit()
  File "/usr/lib/python3.9/_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None
fervent cradle
fervent cradle
fervent cradle
#

exactly!

#

damn

lost lodge
fervent cradle
#

i keep getting TypeError: BridgeSlashGroup.__init__() missing 1 required positional argument: 'callback' from this code:

class Tags(commands.Cog):
  def __init__(self, bot, a):
      self.bot = bot

  @bridge.bridge_group(invoke_without_command=True)
  async def tag(self, ctx):
      await ctx.respond("Subcommand not found.")

  @tag.command(
      name="add"
  )
  async def add(self, ctx):
      await ctx.respond("test")

does anyone know the problem?

white wadi
#
    async def regen_button_callback(self):
        exit()```
white wadi
#

oh and the callback is bad

fervent cradle
white wadi
#

i didnt change the name

young bone
#

also you have to do an interaction

#

await interaction.response.send_message("")

white wadi
#

it doesnt give an error, but the bot is still on

fervent cradle
#

oh

#

ok wait

#

os._exit(1) should work

#

without try/except

fervent cradle
young bone
fervent cradle
white wadi
#

thanks

fervent cradle
rare ice
#

@fervent cradle Please don't cross post.

rugged lantern
#

you cope, that's what you're gonna have to do until someone answers you

rare ice
#

Choose either your help thread or this thread, not both.

fervent cradle
rare ice
#

Next time it will be a warning.

fervent cradle
#

alr

dry echo
#

is there a way to get the user count of the bot without the member intent?

rare ice
#

if you don't have the members intent any list of members from a guild will return [] iirc

dry echo
#

so i cant even get the User object without the intent?

rare ice
#

not necessarily. I believe you can but the member intents is just for guild.members and bot.users. Not 100% sure since I haven’t read the docs on what it is specifically yikes

#

you can still access ctx.author and interaction.user and stuff like that

dry echo
#

but i only need the user count, without any events or commands sadge

dry echo
fervent cradle
#

anyone happens to know how to make ur own author_check in a paginator?

cyan quail
#

or i guess specifically set the paginator.usercheck attribute to it

fervent cradle
#

How can I fix this?

@bot.bridge_command()
async def email(ctx, email):
    
    api.set_query(email)
    api.set_type('email')
    result = api.lookup()
    embed = discord.Embed(title="Email command", color=discord.Color.random())
    embed.add_field(name="Test", value=item['line'], inline=False)
    for i, item in enumerate(result):
        if i == 20: break
        await ctx.channel.send(embed=embed)
neat temple
fervent cradle
#

bruh 🤣

fervent cradle
#

i was trying out the code snippet in the docs and came across this:

class MyView(discord.ui.View):
    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "Choose a Flavor!", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maximum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Vanilla",
                description="Pick this if you like vanilla!"
            ),
            discord.SelectOption(
                label="Chocolate",
                description="Pick this if you like chocolate!"
            ),
            discord.SelectOption(
                label="Strawberry",
                description="Pick this if you like strawberry!"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")

@bot.command()
async def flavor(ctx):
    await ctx.send("Choose a flavor!", view=MyView())
#

any idea how do i get rid off the the application did not respond message?

full basin
#

You respond to interactions

fervent cradle
#

instead of ctx.send?

young bone
#

if you use discord.Bot yes

fervent cradle
#

i see

#

that solved it, thanks a lot 👍

lost lodge
#

hello i have that error:

AttributeError: 'permanent' object has no attribute 'add_view'```
#

code:

import discord
from discord.ext import commands
from discord.ui import Button, View
from views.ticket_View import MyView


class permanent(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        self.add_view(MyView())

def setup(bot):
    bot.add_cog(permanent(bot))```
full basin
#

Read your error.

#

And read your code.

lost lodge
full basin
#

Literally read your add_view line and you'll see what's wrong

#

This is problem solving skills.

lost lodge
full basin
#

self. Is the class.

lost lodge
#

just add_view?

full basin
#

Add_view is a bot method

lost lodge
#

bruh

#

self.bot.add_view

full basin
#

Congrats. You did it yourself.

lost lodge
#

thanks

lost lodge
warm kindle
#

hello

#

how can i do a handler ?

lost lodge
young bone
warm kindle
clever nova
#

How do you send a message to a different channel than the one the slashcommand was invoked from without errors?
When i use this snipet, it actually sends the message to the given channel, but it also sends this error message in response to the slashcommand,

async def create_new_bet(
    ctx: discord.ApplicationContext, 
    question: Option(str, "Pregunta de la prediccion."), 
    channel: Option(discord.TextChannel, "Canal donde se publicara esta prediccion."),
):
    await channel.send(content=f"Encuesta: {question}")

bot.run(DISCORD_TOKEN)```
lost lodge
#

ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout```
#

what is the problem it works with other views

#
import discord
from discord.ext import commands
from discord.ui import Button, View
from views.ticket_View import OpenTicketView
from views.ticket_View import TicketView


class permanent(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        self.bot.add_view(OpenTicketView())
        self.bot.add_view(TicketView())

def setup(bot):
    bot.add_cog(permanent(bot))````
#
class TicketView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None) # timeout of the view must be set to None

    @discord.ui.button(label="Close", style=discord.ButtonStyle.red)
    async def first_button_callback(self, button, interaction):
        await interaction.response.send_message("You pressed me!")

    @discord.ui.button(label="Claim", style=discord.ButtonStyle.gray)
    async def second_button_callback(self, button, interaction):
        button.disabled = True  # set button.disabled to True to disable the button
        button.label = "No more pressing!"
        await interaction.response.send_message("You pressed mesad!")```
lost lodge
silver moat
#

each persistent view you add must have it's own custom_id

young bone
#

I also cannot be the same custom_id each button

fleet tusk
#

Please help, how can I edit "select" created in one function from another, having message id
I try to use that, but nothing work

mes_with_select_id = m_ids["Categories_of_item"][0][f"{reaction.message_id}"]
            mes_with_select = await channel.fetch_message(mes_with_select_id)
            select: SelectMenu = mes_with_select.components[0].children[0]
            select.disabled = True
woeful spindle
#

hey, how can i check if a user is banned?

woeful spindle
silver moat
zinc minnow
#

hello guys, who can help with the question? how to get the name of the user who clicked on the button
ping please

zinc minnow
#

thx

#

I could not find it due to the fact that it is not in the pycharm prompts

woeful spindle
zinc minnow
#

ok thx

silver moat
rare ice
woeful spindle
#

it’s fixed now :)

sinful laurel
#
import discord
import os # default module

bot = discord.Bot(debug_guilds=[...])

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(name = "hello", description = "Say hello to the bot")
async def hello(ctx):
    await ctx.respond("Hey!")

bot.run(os.environ['TOKEN'])```
it keeps giving me this error. I thought it was a me issue before I literally just copied the official starter bot tutorial. Everything is installed correctly (at least i think) I already followed all the instructions inculdin disabling auto install
fervent cradle
obtuse juncoBOT
sinful laurel
#

even if i do that it wont work

sinful laurel
# full basin ?tag replit

could you read the question once again "followed all the instructions inculdin disabling auto install"

sinful laurel
fervent cradle
#

that is very weird

#

idk

sinful laurel
#

if even the official templates arent working then i probably installed it wrong

#

but I already followed all the instructions to prevent dpy from installing

#

py-cord is also installed

#

anyone?

#

I have to finish this by 5:30 or something

#

`ok just created a new repl and it worked

#

ok

flint breach
#

anyone know a fast way to check if a user is in any vc the bot can see?

zealous lark
#

can channel.send can be ephemeral -ed? like private so only the one user can see it?

zealous lark
silver moat
#

Well, imagine this being abused so it floods your chat

sharp smelt
#

How do I react to my own message? I tried await ctx.add_reaction("🤣") but it didn't work.

flint breach
silver moat
sharp smelt
silver moat
sharp smelt
fleet tusk
#

Is it possible to make the button work after the bot is restarted and it would not have to be sent again?

errant craneBOT
#

Here's the persistent example.

silver moat
#

@fleet tusk^

#

yw

fleet tusk
#

Thanks

flint breach
sharp smelt
#

Am I missing something?

silver moat
sharp smelt
#

ok

sharp smelt
silver moat
sharp smelt
#

ok

sharp smelt
flint breach
#

are you able to use emojis in the placeholder for the select drop down? and if so how?

rare ice
rare ice
#

np

flint breach
# rare ice np

wait just to clarify, i can use default emojis in the placeholder right?

rare ice
#

Yes

flint breach
#

i dont see in the docs where id set the label for the placeholder

flint breach
sharp smelt
#

How do I make a slash command with a space in it?

sharp smelt
#

It's just how Discord made it

sharp smelt
#

If you want everything to fit you can put a \ infront of the emoji to show the original so 💡 becomes \💡with \:bulb:

flint breach
flint breach
sharp smelt
flint breach
#

ahh your right i just tried it with my bot too

#

idk then

sharp smelt
#

I just found out I need to make a slash command group for each word

flint breach
#

ohhh ok, also good to know lol

sharp smelt
#

Yeah

rigid sable
flint breach
#

this should delete the message 10 seconds after its sent right? doesnt seem to be working for me
await ctx.send_response(content=error,delete_after=10,ephemeral=True)

silver moat
flint breach
#

aww man

#

thanks tho

rare ice
flint breach
#

ohh ok. idk why the other was working then

rare ice
#

send_response isn’t a method of ctx or commands.Context.

flint breach
#

well i changed it and it broke so ¯_(ツ)_/¯

#

ill just leave it

fervent cradle
#

so I was using the music bot example with the help of wavelink, mentioned in the docs, I setup a lavalink server and all, but everytime the command is executed I get this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('my lavalink server url with song name ')
google says it's because no output is being passed?

any help would be appreciated

naive steppe
#

how do i read an embed for information?

say i have one containing a key and id, how do i go about using a bot to format that information into id:key
i have a channel these are logged to but lost the file containing it, so i want to rebuild the file using a bot without looking at all the messages

@Bot.slash_command(name="build_users", description="Builds auth list by reading log channel")
async def build_users(ctx: discord.ApplicationContext):
    if ctx.author.id == 294503472307372034:
        messages = await ctx.channel.history(limit=None).flatten()
        for message in messages:
            try:
                word = ""
                for x in message.embeds[0].fields:
                    if x.name == "ID":
                        word+=str(x.value) + ":"
                    if x.name == "KEY":
                        word+=x.value
                print(word)
            except:
                pass
flint breach
#

how do you add options to a slash command in a cog?

young bone
#

self, ctx, text,

#

?

naive steppe
#

async def add_auth(ctx: discord.ApplicationContext, user: Option(discord.User, "Input a user to add to auth list!")):

#

change "discord.User" out with anything you want

#

str for string
int for int
ect

flint breach
naive steppe
flint breach
# naive steppe mind sending an example of your code?
async def toggle_light(
        self,
        ctx,
        deviceName: discord.option(
        name="deviceName",
        input_type=discord.SlashCommandOptionType.string,
        description="(Optional) Name of the device",
        required=False
    ),
        deviceID: discord.option(
            name="deviceID",
            input_type=discord.SlashCommandOptionType.string,
            description="(Optional) ID of the device",
            required=False
        )
    ):
naive steppe
#

"Option" not "option"

#

they are different

#

mid sending your full count code with "
```py
code here
```
"

#

^

flint breach
fervent cradle
#

Why do I get "Converting to "Option" failed for parameter "command"." when using bridge ?

naive steppe
#

yes

naive steppe
fringe socket
naive steppe
#

whats your issue? mind posting your code with
```py
(code here)
```

fringe socket
#

My bot doesn't remove their reaction

#
@bot.event
async def on_message(message: discord.Message):
    emoji = '🆕'
    await message.add_reaction(emoji)
    await asyncio.sleep(10)
    await message.remove_reaction(emoji='🆕',member=(1005312021836869795))
#

@naive steppe

naive steppe
#

whats the point of member?

fringe socket
#

I'm trying to make the bot remove their own message

#

*reaction

#

but I don't know how

#

The adding worked, the removing did not

naive steppe
#
reaction = await message.add_reaction(emoji)

await message.remove_reaction(emoji, reaction.author.id)
#

try this

naive steppe
lost lodge
#

how can i get an message id from a interaction respond message

#
global close_message
        close_message = await interaction.response.send_message("Are you shure?", view=CloseTicketView())```
#
msg = await interaction.channel.fetch_message(close_message.id)
        await msg.delete()```
naive steppe
#

remove_reaction doesnt take "member"

fringe socket
#
AttributeError: 'NoneType' object has no attribute 'author'

@naive steppe

lost lodge
#

?

#

help pls

zinc minnow
#

how to add reaction to modal embed?

#

(interaction)

naive steppe
#

like an emoji?

white wadi
#

Whats wrong with this line of code? i tried doing it like id=int and it didnt work too


TypeError: get_or_fetch_user() missing 1 required positional argument: 'id'```
cyan quail
naive steppe
hidden oxide
#

How to use @client.event if i run bot?bot.run()

young bone
#

basic python?

lost lodge
young bone
lost lodge
#

ah

young bone
#

at the event

lost lodge
#

sorry 🙂

lost lodge
young bone
#

in a cog ist @commands.Cog.listener()

lost lodge
lost lodge
cyan quail
#

It's interaction.delete_original_message

lost lodge
# cyan quail It's interaction.delete_original_message

i get an error:

class CloseTicketView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None) # timeout of the view must be set to None

    @discord.ui.button(label="Yes", custom_id="button_4", style=discord.ButtonStyle.red)
    async def button_4_callback(self, button, interaction):
        await interaction.response.send_message("You pressed me!")
        await interaction.channel.delete()

    @discord.ui.button(label="No", custom_id="button_5", style=discord.ButtonStyle.gray)
    async def button_5_callback(self, button, interaction):
        await interaction.delete_original_message()````
#

discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

cyan quail
#

Oh other way round

lost lodge
#

?

cyan quail
#

Replace interaction with close_message

lost lodge
#

thanks!

hidden oxide
young bone
#

lol

fervent cradle
#

how exactly would I implement this in my bot?

young bone
#

same like the other stuff?

hidden oxide
#

Do u know how to fix this:

TypeError: Client.event() missing 1 required positional argument: 'coro'
#

@young bone

hidden oxide
#

@discord.Bot.event

young bone
#

why discord.Bot.event???????

hidden oxide
hidden oxide
naive steppe
#

it would be @Bot.event()
or what ever you named your bot in code
example:

Bot = discord.Bot()

@Bot.event
async def on_ready():
    print(f'We have logged in as {Bot.user}')
young bone
#

^

white wadi
cyan quail
white wadi
#

oh sh*t, i forgot

hidden oxide
#

I don't know i try all options. But nothing work.
Here i add bot, some know, whats the problem

 
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Создать товар", style=discord.ButtonStyle.primary, custom_id="persistent_view:item_sell")
    async def item_sell_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        modal = Modal(title='User Details')
        await interaction.response.send_modal(modal)


class PersistentViewBot(discord.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix=commands.when_mentioned_or("!"), intents=intents)
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:

            # Register the persistent view for listening here.
            # Note that this does not send the view to any message.
            # In order to do this you need to first send a message with the View, which is shown below.
            # If you have the message_id you can also pass it as a keyword argument,
            # but for this example we don't have one.
            self.add_view(PersistentView())
            self.persistent_views_added = True

        print(f"Logged in as {self.user} (ID: {self.user.id})")
        print("------")


bot = PersistentViewBot()
fervent cradle
#

I'm new to pycord sorry

naive steppe
#

so ctx.channel.is_nsfw() returns true / false

#

example:

channel = Bot.fetch_channel(id)
print(channel.is_nsfw())
fervent cradle
#

i see

#

thanks a lot

fervent cradle
lost lodge
#

why does my self.bot gives a error?
error:

Failed to load extension "ticket_normal"
ExtensionFailed: Extension 'cogs.ticket.ticket_normal' raised an error: NameError: name 'self' is not defined```
lost lodge
#

help pls

naive steppe
#

You prolly mean messages

fervent cradle
#

the slash interaction

naive steppe
#

Not the Bot object

#

You would use ctx

fervent cradle
#

I figured it out by reading docs, thanks for helping out :D

tribal rain
tribal rain
lost lodge
# tribal rain How do you load the extensions?
def load_commands(command_type: str) -> None:
    for file in os.listdir(f"./cogs/{command_type}"):
        if file.endswith(".py"):
            extension = file[:-3]
            try:
                bot.load_extension(f"cogs.{command_type}.{extension}")
                print(f'Loaded extension "{extension}"')
                print("-------------------")
            except Exception as e:
                exception = f"{type(e).__name__}: {e}"
                print(f'Failed to load extension "{extension}"\n{exception}')
                print("-------------------")




if __name__ == '__main__':
    load_commands("antiraid")
    load_commands("bot")
    load_commands("mail")
    load_commands("giveaway")
    load_commands("help")
    load_commands("poll")
    load_commands("moderation")
    load_commands("ticket")
    load_commands("view")````
tribal rain
#

Why don't you use this?

extentions=[
            'cogs.ticket',
]
if __name__ == "__main__":
    for extension in extentions:
        try:
            bot.load_extension(extension)
        except Exception as e:
            print(f'Error loading {extension}', file=sys.stderr)
            traceback.print_exc()
#

Maybe it might work

tribal rain
lost lodge
tribal rain
lost lodge
# tribal rain What is the error now?
Error loading cogs.ticket
Traceback (most recent call last):
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/cog.py", line 731, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Development/Python/in-progress/dsfsdf/cogs/ticket/ticket_normal.py", line 38, in <module>
    class Ticket(commands.Cog):
  File "/Development/Python/in-progress/dsfsdf/cogs/ticket/ticket_normal.py", line 70, in Ticket
    channel54 = self.bot.get_channel("1023575071903731833")
NameError: name 'self' is not defined

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

Traceback (most recent call last):
  File "/Development/Python/in-progress/dsfsdf/main.py", line 81, in <module>
    bot.load_extension(extension)
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/cog.py", line 882, in load_extension
    loaded = self.load_extension(".".join(parts), package=package, recursive=recursive, store=store)
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/cog.py", line 867, in load_extension
    self._load_from_module_spec(spec, name)
  File "/Development/Python/in-progress/dsfsdf/venv/lib/python3.10/site-packages/discord/cog.py", line 734, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.ticket.ticket_normal' raised an error: NameError: name 'self' is not defined```
lost lodge
silver moat
#

that's not a cog. that's a view

tribal rain
lost lodge
#

ok

silver moat
#

that says view

copper dew
#

the slash command is defined with the MyView class

silver moat
#

The indentation indicates that the slash command is still IN THE VIEW.

#

not in the cog

#
class addons(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.slash_command(description="Card Information")
    async def cards(self, ctx):
        await ctx.respond("pls select at the options", view=MyView())
#

this would be in the cog

tribal rain
# lost lodge ok
@commands.command(aliases=['add-user', 'ticket-add  '])
    @commands.has_any_role("「TEAM」")
    async def add_user(self, ctx, member: discord.Member):
        if ctx.channel.name.startswith('ticket-'):
            await ticket_perms(member, ctx.channel)
            await ctx.reply(f"I've succesfully added {member.mention} to this ticket!")
        else:
            await ctx.reply("You are not in a ticket-channel!")
tribal rain
lost lodge
tribal rain
silver moat
# lost lodge why does my self.bot gives a error? error: ```py Failed to load extension "ticke...
@commands.command(aliases=['add-user', 'ticket-add  '])
@commands.has_any_role("「TEAM」")
async def add_user(self, ctx, member: discord.Member):
        if ctx.channel.name.startswith('ticket-'):
            await ticket_perms(member, ctx.channel)
            await ctx.reply(f"I've succesfully added {member.mention} to this ticket!")
        else:
            await ctx.reply("You are not in a ticket-channel!")

global channel54
channel54 = self.bot.get_channel("1023575071903731833")

self can only be used inside of a method the self.bot.get_channel is outside of any method.

lost lodge
#

so it needs to be in a command/event?

silver moat
#

you can put it in __init__

#

also get_channel takes an int, not a string

lost lodge
#

ok

lost lodge
silver moat
#

clearly you already did, but you may ask another one

lost lodge
# silver moat clearly you already did, but you may ask another one

so i've imported a function from the file(wright path)

import discord
from discord.ext import commands
import asyncio
import chat_exporter
import io
from cogs.ticket.ticket_normal import ticket_perms



class OpenTicketView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)


    @discord.ui.button(label="Open a Ticket!", emoji="🎟️", custom_id="button_1", style=discord.ButtonStyle.green) # the button has a custom_id set
    async def button_1_callback(self, button, interaction):
        cat = discord.utils.get(interaction.guild.categories, name="▼ SUPPORT ▼")
        channel = await interaction.guild.create_text_channel(name=f"ticket-{interaction.user.name}", category=cat)
        await interaction.response.send_message(f"<#{channel.id}>", ephemeral=True)
        perms = channel.overwrites_for(interaction.user)
        await ticket_perms(interaction.user, channel)
        global ticket_user
        ticket_user = interaction.user.mention
        embed=discord.Embed(title=f"Welcome to your ticket {interaction.user.name}!", description=f"We are trying to help you as quickly and well as possible!")
        await channel.send(f"<@&1018110133563297810> – {interaction.user.mention}", embed=embed, view=TicketView())```
#

but i've got an error:

#
Failed to load extension "mail"
ExtensionFailed: Extension 'cogs.mail.mail' raised an error: ImportError: cannot import name 'OpenTicketView' from partially initialized module 'views.ticket_View' (most likely due to a circular import) (/Development/Python/in-progress/dsfsdf/views/ticket_View.py)
-------------------
Failed to load extension "ticket_normal"
ExtensionFailed: Extension 'cogs.ticket.ticket_normal' raised an error: ImportError: cannot import name 'ticket_perms' from 'cogs.ticket.ticket_normal' (/Development/Python/in-progress/dsfsdf/cogs/ticket/ticket_normal.py)
-------------------
Failed to load extension "permanent"
ExtensionFailed: Extension 'cogs.view.permanent' raised an error: ImportError: cannot import name 'OpenTicketView' from partially initialized module 'views.ticket_View' (most likely due to a circular import) (/Development/Python/in-progress/dsfsdf/views/ticket_View.py)````
silver moat
#

simplest solution I can think of that won't overcomplicate things

#

hopefully.

lost lodge
#

i did that but my code look dies

golden lake
#

do interaction option autocomplete errors not get printed to stderr by default? im getting the "loading options failed" error message in the discord client UI but nothing indicating an error in the bot logs. only see application_command_auto_complete being dispatched then nothing

silver moat
golden lake
#

the only error i can see maybe being in here is that im trying to read ctx.cog, assuming that would get me access to the cog's self attributes.

#

def _list_by_prefix(ctx: AutocompleteContext) -> Optional[dict]:
    if ctx.command.name == "enable":
        state = True
    elif ctx.command.name == "disable":
        state = False
    else:
        return None

    prefix = None
    if ctx.value:
        prefix = ctx.value.lower().replace(" ", "_")

    tasks = list()
    for name, attr in ctx.cog.jobs.items():
        if (
            not attr["guild_iterable"]
            or attr["state"] == state
            or (prefix and not name.startswith(prefix))
        ):
            continue
        tasks += name.replace("_", " ")

    return tasks
#

shouldnt take too long. its just iterating a small dict and returning matching items or an empty list

copper dew
#
@bot.event 
 async def on_ready():
     await bot.change_presence( 
         activity=discord.Activity(type=discord.ActivityType.watching, name="/help") 
     )

This is what I have set up on my bot

silver moat
#

split it into 2 change_presences?

lost lodge
#

i wanted to import the channel but it gets an error

hidden oxide
#

It's imposible add event to bot

#

They can only listen

rugged lantern
#

what version was bridge commands added to pycord?

rugged lantern
#

specifically which b version

full basin
#

Show your pip freeze

fossil canopy
#

verifikation_view = View(verifikation_button) throws this error : TypeError: View.init() takes 1 positional argument but 2 were given

woeful spindle
#

how do I edit a .respond() message? for example, im using:

await ctx.respond("test")

so how do I edit that message?

woven gale
young bone
woven gale
#

I fixed it, but now comes

    bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
woven gale
full basin
#

Open your terminal and run pip freeze

silver moat
silver moat
silver moat
woven gale
silver moat
woven gale
silver moat
#

and click enter

woven gale
silver moat
#

yw

verbal gulch
#

hey hello

#

why i get this error?

#
Ignoring exception in on_interaction
Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 1201, in _invoke
    await command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 356, in invoke
    await self.prepare(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 278, in prepare
    if not await self.can_run(ctx):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 373, in can_run
    local_check = cog._get_overridden_method(cog.cog_check)
AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'


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

Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1009, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 359, in invoke
    await injected(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1058, in on_interaction
    await self.process_application_commands(interaction)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 756, in process_application_commands
    await self.invoke_application_command(ctx)

#
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1013, in invoke_application_command
    await ctx.command.dispatch_error(ctx, exc)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 401, in dispatch_error
    local = cog.__class__._get_overridden_method(cog.cog_command_error)
AttributeError: type object '_MissingSentinel' has no attribute '_get_overridden_method'
Ignoring exception in command break accept:
Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 1201, in _invoke
    await command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 356, in invoke
    await self.prepare(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 278, in prepare
    if not await self.can_run(ctx):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 373, in can_run
    local_check = cog._get_overridden_method(cog.cog_check)
AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
#
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1009, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 359, in invoke
    await injected(ctx)
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
full basin
#

Posting it 5 times for what

silver moat
verbal gulch
#

no, that's one error

#

posted one time

#

the error is just long

undone smelt
#
    @commands.Cog.listener(name="on_application_command")
    async def on_application_command_listener(self, ctx: discord.ApplicationContext):
        """Fires after an app command is used."""
        self.bot.console.log(f"{ctx.author.name} used {ctx.command.qualified_name}")  # type: ignore

Is there a I can also print whatever arguments were used in the command?

woven gale
#

How can my bot send a webhook? (As embed)

fervent cradle
#

hey, could anyone tell me why its not good to use urllib / requests in a discord bot? i read you shouldnt use it but i want to know why

rare ice
#

for an autocomplete function, what parameters does it take? ctx and interaction?

rare ice
errant craneBOT
#

examples/app_commands/slash_autocomplete.py lines 92 to 102

async def color_searcher(ctx: discord.AutocompleteContext):
    """
    Returns a list of matching colors from the LOTS_OF_COLORS list.

    In this example, we've added logic to only display any results in the
    returned list if the user's ID exists in the BASIC_ALLOWED list.

    This is to demonstrate passing a callback in the discord.utils.basic_autocomplete function.
    """

    return [color for color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED]```
silver moat
#

@rare ice

rare ice
#

oh ok just ctx, thanks

limber bison
#

Ive been looking but idk how to word it for the docs. How would i sent a message in a specific channel without a command?

#

or edit for that matter

full basin
limber bison
#

like i want to just write and have it execute

#

not write then go run a slash command

silver moat
#

you can get a channel object with guild.get_channel(id) or await guild.fetch_channel(id)

limber bison
#

ty

woven gale
#

Can anyone help me?

import discord
from discord.ext import commands
from discord.commands import slash_command
from discord import Webhook
import aiohttp


class Greet(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @slash_command()
    async def greet(self, ctx):
        await ctx.respond(f"Hey {ctx.author.mention}")

    @commands.Cog.listener()
    async def on_member_join(self, member):
        async with aiohttp.ClientSession() as session:
            webhook = Webhook.from_url('https://discord.com/api/webhooks/1023657529860952207/YRs6RdI_SQ3cBp0KZbp-o4-MrbfbPryvCvyvKlrQ9BXmpIxlSEPeWloxRP9ZSgAvs0eU', session=session)

        channel = await self.bot.fetch_channel(1023645698551463967)
        await webhook.send(embeds=webhook)


def setup(bot):
    bot.add_cog(Greet(bot))
fervent cradle
#

nice webhook url

young bone
#

F

woven gale
#

Why?

young bone
#

and dont show the webhook url

fervent cradle
#

remove the webhook url from code

woven gale
#

Its a test webhook and a test server xD

full basin
#

"embeds=webhook"

woven gale
full basin
#

No what lmao

woven gale
#

Dont work

full basin
#

It's your own code. I'm remarking your error

woven gale
full basin
#

Because that line is wrong

#

That's your problem. You solve it.

#

It's not a hard fix.

woven gale
#

Nice help. 👍 (irony)

full basin
#

Helping is not solving it for you chief.

#

You're literally doing embeds=webhook. webhook is not even a list of embed objects. Isn't even an embed object.

woven gale
full basin
#

Actual embed objects?...

woven gale
#

I have it already but it dont work anyway await embed.send(embeds=embed)

full basin
#

What the hell is that

#

Do you even know what an embed is?

woven gale
#

Yes

full basin
#

Then?

full basin
woven gale
#

await webhook.send(webhooks=webhook)

?

full basin
#

You definitely don't know how this works.

woven gale
full basin
#

webhook.send is the same as ctx.send or channel.send or ctx.respond

full basin
#

The embeds kwarg takes a LIST of EMBED OBJECTS that you provide

lost lodge
#

how can i get an channel in a view class?

#

(i wanna send a message in a other channel)

woven gale
full basin
#

Or iirc interaction.guild has a get_channel method. Don't quote me on that

lost lodge
#

thanks

silver moat
#

don't expose your webhook url

fervent cradle
woven gale
full basin
#

At this point. I'll just assume you don't even know python.

woven gale
woven gale
fervent cradle
#

yeah but spoonfeeding isnt learning

full basin
#

What he said

woven gale
full basin
#

You're just impatient and not reading your own code.

#

Not how programming works sadly.

woven gale
#

just say it please

fervent cradle
woven gale
#

Now its this

full basin
#

Yup, you messed up again. Show your code.

woven gale
#
import discord
from discord.ext import commands
from discord.commands import slash_command
from discord import Webhook
import aiohttp


class Greet(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @slash_command()
    async def greet(self, ctx):
        await ctx.respond(f"Hey {ctx.author.mention}")

    @commands.Cog.listener()
    async def on_member_join(self, member):
        async with aiohttp.ClientSession() as session:
            embed = Webhook.from_url("URL", session=session)

        channel = await self.bot.fetch_channel(1023665540910284831)
        await webhook.respond("<@user.mention> Welcome.", webhooks=webhook)


def setup(bot):
    bot.add_cog(Greet(bot))
fervent cradle
#

webhooks dont have anything to 'respond' to

woven gale
fervent cradle
#

try and see

silver moat
full basin
#

There's no webhook object lmao

woven gale
#

I just replaced url

full basin
#

What about you go over the basics of "variables" on python

#

Hope that makes it clear

#

Oh, and assuming you'd replace respond with send, the send method has no such webhooks kwarg

woven gale
#

So what should I write in the line?

#

Please tell me, I want to read this tomorrow, but the code should be ready today.

silver moat
full basin
#

Listen. Not tryna be a bad person, but this is basic python.

#

Variables are the most basic python

full basin
#

No. I won't spoonfeed you.

#

Nor think anyone here will do

fervent cradle
fervent cradle
silver moat
#

*example

full basin
#

What

silver moat
#

yeah bruh

full basin
#

Girl. I'm not the one that needs help

silver moat
#

your english is shockingly worse than my code

fervent cradle
#

still better than my js

silver moat
#

I don't think they know what the code in their banner does

naive steppe
#

Cant believe people still mix up your and your'erue'r in 2022 smh

rugged lantern
#

i think someone off da perc

fervent cradle
#

Anyone knows how i would go about creating a command which would fetch all users with a certain tag, something like dyno has "/discrim"?

full basin
#

Go over your users cache

dry echo
#

does message.edit() only change the things i pass into it or the whole message?

dry echo
#

so when i have a message with an embed and i dont pass the embed in edit() my embed stays right?

cyan quail
#

yes

dry echo
#

thanks!

dry echo
#

whats the difference between these two?

obj = discord.Embed(title="bla")
obj1 = obj

obj1 = obj.copy()
little hill
#

Is there a limit on how many tags a forum channel can have?

silver moat
near hollow
#

So I know I can send multiple embeds with .send(embeds=listofembeds) but I want to attach a view to each embed but it doesn't seem that views=listofviews works. Any suggestions ?

cyan quail
#

they attach to the entire message

near hollow
#

Ah shucks I see, hmmmmm.

undone smelt
#

how would i pass arguments to a command callback?
In this example, how might I pass something to my_string? Is that even possible?

async def example_command_callback(ctx: discord.ApplicationContext, my_string):
    """Callback function called with manually-made command"""
    await ctx.respond(f"Woop! {my_string}")

class ExampleCog(commands.Cog):
    def __init__(self, bot: PlaygroundBot):
        self.bot = bot

        example_command = discord.SlashCommand(example_command_callback)
        self.bot.add_application_command(send_view_with_manually_made)

def setup(bot):
    bot.add_cog(ExampleCog(bot))
limber bison
#

is there a way to have the bot not display the attachments URL?

naive steppe
undone smelt
cyan quail
peak chasm
#

how to use .edit whit message_id ?

peak chasm
#

If it doesn't recognize me, the get_message works the same, doesn't it?

silver moat
#

yes

silver moat
peak chasm
#

I think not, I haven't updated it for a long time.

silver moat
#

pip list in terminal and show stdout

peak chasm
#

what would be the command line to update? pip upgrade pycord?

silver moat
#

?tag install

obtuse juncoBOT
#
  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

silver moat
#

2b

peak chasm
#

oh I changed the library a long time ago due to a problem.

silver moat
peak chasm
#

there I changed it again, I can't believe I use another library xd

silver moat
#

so you are using py-cord?

peak chasm
#

yes

#

now if i take it

silver moat
#

you uninstall discord.py, right?

peak chasm
#

yes

silver moat
#

because they cause conflicts

#

ok so it should work

peak chasm
#

Yes, but the content is not changed.

#

I get an error in the .edit

silver moat
#

send error

#

w/ full traceback

peak chasm
#

I don't see the error because I have a try except :'v

silver moat
peak chasm
silver moat
#

what is the message

peak chasm
#

the message to change is another similar 6 numbers

silver moat
#

so your bot sent the message?

peak chasm
#

if the bot sends the message a long time ago, but does not edit it.

silver moat
peak chasm
#

would I have to send the message and then edit it? like new

silver moat
#

you can use

guild = await bot.fetch_guild(guild_id)
message = await guild.fetch_message(message_id)
await message.edit()
peak chasm
#

guild id ? the rol ?

#

or channel ?

peak chasm
#

there I solved it, I used what you sent me first and I put that if it fails, delete the message.

#

will someone have a countdown with emojis?

silver moat
peak chasm
vapid pumice
#

Does message.content naturally not register inside of a class?

#

Intents are set globally

#

and it works outside of the class just fine

fierce elm
#

does the discord.ext.pages.PaginatorButton.callback override the navigation function of the button? or can I use the button to also update the custom_view I have in a page

fringe socket
#

Hello! How do I make a command alias?

sinful pivot
#

I kind of forgot, what's the best way to set a status(I'm pretty sure the best one is when you set it when you define the bot variable, though I can't find what I need to set so yeah)

sinful pivot
#

on_ready can be called multiple times, and it could mess stuff up

#

I know for a fact that I shouldn't be using on_ready to set statuses.

#

I forgot how to set them before that or smth like that

#

I think it's status

cobalt tangle
#

Extension 'cogs.fun' raised an error: AttributeError: 'Bot' object has no attribute 'add_command' Why am I getting this error

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

my setup function is correct ig?

#
class Fun(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
cobalt tangle
cobalt tangle
cobalt tangle
cobalt tangle
peak chasm
cobalt tangle
#

i guess u can but it would be complex, i would suggest buttons

#

U would have to wait for a reaction then register the user and then remove the reaction if the user does it again

peak chasm
#

yes, last I will do something simple with text.

cobalt tangle
cobalt tangle
cyan quail
cobalt tangle
#

add_command?

cyan quail
#

you have a line in your cog that's doing bot.add_command

cobalt tangle
#

its add_cog

cyan quail
#

show the file

cobalt tangle
#

wait

cobalt tangle
cyan quail
#

can you also paste the full error

cobalt tangle
#

k

cyan quail
#

oh you're using the wrong type of bot probably

cobalt tangle
#

?

#

discord.Bot

#

is being used

cyan quail
#

nope needs to be commands.Bot from discord.ext.commands

cobalt tangle
#

Then how do i use discord.Bot

cyan quail
#

you don't, if you want prefix commands you use commands.Bot

#

which inherits from discord.Bot

cobalt tangle
#

Okay

#

it works now

#

thanks

golden lake
#

i have now tried to get slash cmd autocomplete working in a myriad different ways and they just

#

dont. work. at all.

#

global CHOICES
CHOICES = [
    "anteater",
    "berry",
    "crustacean",
    "option"
]


@slash_command(name="cmd")
@option("opt", description="An option", autocomplete=CHOICES)
async def test_slash_cmd(ctx: ApplicationContext, opt: str):
    """Are you feeling lucky?"""
    await ctx.respond(f"You selected {opt}!")


def setup(bot: Bot):
    bot.add_application_command(test_slash_cmd)
#

this is incredibly simple. the command is being loaded via an extension and registered with the bot's guilds

errant craneBOT
#

Here's the slash autocomplete example.

golden lake
#

but i still get "Option loading failed" in the client

#

ive read it dude

#

ive read that, the pycord guide, etc.

#

ive read the internal help for @option, etc.

#

ive tried passing [str, ...], ive tried using discord.utils.basic_autocomplete([str, ...])

#

nothing works. im on v2.1.3

young bone
#

do you have something else installed?

golden lake
#

what

young bone
#

show the pip list

golden lake
#

yes of course i do. its a massive bot

#

all my slash commands work fine. but trying to add choices or autocomplete doesnt work at all

#

do you know if i have to do anything custom since im using a custom, overloaded application context?

#

i tried overwriting the AutocompleteContext to add references to the custom ApplicationContext but that didnt help either

#

this is super frustrating because im getting no errors at all

#

im seeing INTERACTION_CREATE events when i type in the slash cmd option's value, but no exceptions or warnings, nothing

#

nor am i seeing any initialization errors on bot load

#

#1023644401853018194 message

#

it looks like someone else is having this problem and it might be resolved on master

cyan quail
golden lake
#

this is not fixed on master, unfortunately

#

not for slash command groups (which merely fail to register any options), nor bare slash commands (which continue to fail option value loading)

#

@option(choices=...) works on master tho

#

so ig ill go with that for meow

covert loom
#

good day, I'm fairly new to discord bot development, currently trying to set an application.commands scope for my bot, however even though I get it defined in a url it refuses to work for some reason

silver moat
covert loom
#

the bot gets added to the server but I can't see any commands (I did one from the example in the docs)

#

auth screen looks like this, the url is https://discord.com/oauth2/authorize?scope=bot+applications.commands&client_id=my_client_id

copper dew
#

Is the bot online ?

covert loom
#

responds to regular text commands just fine

#

here's the sauce:

import logging
import discord

handler = logging.FileHandler(filename='fc_log.log', encoding='utf-8', mode='w')

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

bot = discord.Bot()


@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')


@bot.command(description="Sends the bot's latency.")
async def ping(ctx):
    await ctx.respond("Pong! My latency is "+bot.latency)


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('token_here')```
woeful spindle
covert loom
#

/ping should be, according to the example

#

(sorry if it sounds super dumb am still new to the api stuff)

copper dew
covert loom
#

wait just read in the docs, says slashes take a while to register unless the specific guild where they're used is utilized... and I didn't set anything there

copper dew
#

When globally loading an slash command, it takes a while (up to an hour irc). But if u specify the guild to load, then it doesn't

rugged lantern
#

why do you use both client and bot

rugged lantern
#

and no slash commands are near instant now

woeful spindle
#

mine are lol

rugged lantern
#

the reason your commands dont work is because you're using both client and bot, of which only client is run by your token

covert loom
#

ahhh, so I should run both?

rugged lantern
#

no

#

you use either of them, but for commands use bot only

covert loom
#

ah got it, thanks

#

yeah I just left the prefixed but didn't understand it would interfere with the slash ones

silver moat
#

global commands are registered just as fast as guild commands.

copper dew
odd silo
errant craneBOT
#

bot.py line 43

@client.slash_command(debug_guilds=[910733698452815912])```
spice oyster
fervent cradle
#

how can i check user's roles after slash command execution?

cyan quail
fervent cradle
grizzled sentinel
odd silo
#

i see

dim flicker
#

How to enter a unique ID in the custom_id of the button, which I will receive later when I click on it

#

I tried using a variable, but no, it's impossible

wooden zenith
#
@bot.slash_command(description="nick")
async def nick(ctx, user):
 if {user.Id} == "1007797339643195455":
    return
 embed = discord.Embed(
        title="success",
        description=f"**nick man is ** {user} ")  
 await ctx.respond(embed=embed)

#

error is

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'str' object has no attribute 'Id'

young bone
#

learn basic python

wooden zenith
#

i tried to code something like that its my first time

wooden zenith
young bone
wooden zenith
#

bro u wanna see shit i coded

#

ik basic python

#

j havent done something like this

#

so it got me messed up

errant craneBOT
#

examples/app_commands/slash_basic.py lines 34 to 38

@bot.slash_command(guild_ids=[...])
async def joined(ctx: discord.ApplicationContext, member: discord.Member = None):
    # Setting a default value for the member parameter makes it optional ^
    user = member or ctx.author
    await ctx.respond(f"{user.name} joined at {discord.utils.format_dt(user.joined_at)}")```
hollow osprey
#

How to enter a unique ID in the custom_id of the button, which I will receive later when I click on it
I tried using a variable, but no, it's impossible

#
@discord.ui.button(emoji=':Trash:', label='Удалить тикет', style=discord.ButtonStyle.gray, custom_id=f"{ticketID}")
hollow osprey
#

If you do this, it works

button.custom_id = f"{ticketID}"
#

But I want to do this when creating the button itself, not when clicking on it

young bone
#

remove the {}

#

or define it...

#

its in the error

hollow osprey
young bone
#

if you define it you dont need the f"{}"

hollow osprey
#
@discord.ui.button(emoji=':Trash:', label='Удалить тикет', style=discord.ButtonStyle.gray, custom_id={ticketID2})
#

I'm stupid I don't understand

young bone
#

you also should take a look at basic python

hollow osprey
#

why can't you just do this and that's it custom_id=f"{ticketID}"

cyan quail
cyan quail
#

globals are just a waste and confuse people, don't bother

#

especially with decorators where it becomes even more finnicky, if button.custom_id = f"{ticketID}" was working then stick with it

#

or just create the button manually and assign the callback separately GuraShrug

proud pagoda
#

Is it possible to subclass the context? If it is, is there a guide on doing that?

errant craneBOT
#

Here's the custom context example.

silver moat
#

@proud pagoda ^

proud pagoda
#

Thanks

hasty spire
#

hello there again, how would i make my module(inside it is a lot of embeds) link it to the main file, is it just like cogs?

hasty spire
#

nvm, it works now idk what i did but it works

stiff fiber
#

Quick question - can select menus be added to modals? The docs say that modals only accept InputTexts

full basin
#

I'm sure it's not a feature yet

stiff fiber
#

Yeah I wasn't totally certain but for some reason I misremembered seeing them in modals before

silver moat
stiff fiber
signal sandal
#

how can i get the bot user count?

silver moat
signal sandal
#

ight

#

smthin like that?

silver moat
signal sandal
#

it will print like 42 or smthin

#

bots in over 700 svrs

#

or just 1