#Basic Pycord Help (Quick Questions Only)
1 messages · Page 23 of 1
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.
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
Eh, it's the same. I like it this way.
k
I guess I'm just being too slow at answering the interaction. 
How can I randomly choose a .png file in a folder without taking too much time?
why would a random choice be performance intensive
the same way what you do like the cogs
Good point. I've optimized it and I still get the same error. I'm confused.
defer?
I'll try, just to see what happens.
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!
on_message(message)....
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
Is the slash command a global slash command or guild-specific?
Oh yeah the slash cmd is global in prod and guild-specific in dev
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
try considering it being a skill issue un-registering the command and re-registering the command
how?
comment, run, uncomment run
How can I make my button work after bot restart
assign the button a custom_id
and add it to the on_ready
check docs under "persistent views"
https://guide.pycord.dev/interactions/ui-components/buttons/
Learn all about implementing buttons in your Discord Bot using Pycord.
also the timeout must be set to none
Can pycord create forum posts?
So basically just create a thread in the forum channel?
Is there a way to add permission to application commands(Context Menus)?
Hello! Is there a way to disable auto-generated imports in Visual Studio Code? They are kinda sneaky. 
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?
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
https://guide.pycord.dev/interactions/ui-components/dropdowns
in the callback, do select.values[0], this will get the first value the user picked, or the only one
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
it’s select.values
got it, ty.
someone help 🫠
send a message with a button that sends the modal
Done! If you have the same problem, here is what to disable to fix it.
i want to send the modal when the user sends the command. like the user sends a message and then the modal pops up
use interaction.send_modal
without an interaction, you cannot send a modal
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
no, only for slash commands
no, i meant that the user uses the command /embed then a modal pops up
can be only done with slash commands I think, not for bridgecommands
^
so no bridge commands 🥲
yeah, but without a slash command there is no interaction. So you cannot respond with anything. Buttons have interactions, so sending a button and making the user click the button will work
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..
full trace back thanks
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
what are you trying to get by using children?
I'm not lol
^ thats my code rn
i mean what are you trying to do?
I just have a TextChannel option and send the view to that channel.
It's a poll command.
ic so it looks like a library problem
I'm using py-cord==2.1.3
make an issue on github
should I downgrade to 2.1?
hm ok
What should be the title?
I've never made a issue like this lol
whatever the error is
Well apparently the prefixes commands aren't working at all
Are you loading the cog
Do you have a setup function
Yes
not a lib issue
Slash command works, hut prefix is not
they didn't super their custom class
But
?tag message-content
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
?tag intents
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)
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Is it possible to put a cooldown on a command only when the if function is true?
you can use dynamic_cooldown(func, ...) where func either returns the Cooldown object or None to bypass the cooldown
maybe i should write the example for it
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
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
ctx.author
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
Sadly, when I do this, I get an AttributeError: 'AutocompleteContext' object has no attribute 'author'
Oh yes, indeed, it works. I'm gonna try to implement that 🙂
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?
can you show the full code? followup.send does work with ephemeral but it may depend on the context
view = DefaultView()
for item in list_items:
view.add_item(DefaultButton(label=str(item), custom_id=str(item)))
await ctx.interaction.followup.send(embed=embed_prompt, view=view)
timed_out = await view.wait()
if timed_out:
view.disable_all_items()
view.stop()
await ctx.interaction.followup.send("Timed out.", ephemeral=True)
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.
im assuming you responded somewhere before this then
and i guess defer
though on that note hm
Yes it works usually I just noticed this in the console when I logged into the server and am confused on why it happened.
did it take longer than 15 minutes?
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 😛
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
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
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?
if it goes beyond 15 mins then the followup won't work anymore
so you'd have to use another message sending method
i'd check not embed.video / not embed.image
Would ctx.interaction be None if it timed out before sending the message?
ctx.interaction will always exist
you could probably get away with ctx.channel.send
maybe include a mention or something though
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
Did you figure this out? I'm getting the same error
I guess I could just try except pass it
Although I don't like adding those to my code
nope
there's nothing wrong with the timeout, it's working as intended
the issue is that you're using followup.send after the token's expired
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?
wrong way
https://docs.pycord.dev/en/master/api.html#discord.ui.View.wait
If True, then the view timed out. If False then the view finished normally.
i dont think that'd work because i only want to use the command if they are true (there is a video etc). The EmbedProxy() makes this always tru tho
it does work
anybody?
Just made a new forum post about it for us: #1022943180930416640
if (not embed.video or not embed.image):
you sure? the logic checks out on my end
ah ok ur logic was correct but its cause i was being a dumbass and reversing the logic for what i needed
fun times
im v sorry but ty for the sanity check
allgood
i am a bit dumb sometimes xD
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
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)
Discord.py is uninstalled in the environment.
- 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
Well that did it, thnx
Discord.py is active again, however, a dozen of days ago I switched to Pycord anyways because of guides and docs being better, at least from what I've seen.
Oh really, well I'm switching back because this isn't working with pycord
And is with discord.py
You can easily migrate by using guides and asking for help here, if you want.
@stiff flame Run pip freeze
hmm, but I'm not sure what is the advantage
I'm sure pycord ain't bad, or that discord.py is better. I just have to go with one and stick with it
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
Why are you defining intents 3 different times
I guess that is the problem, I am confused with the guide
how to disable command usage in dms
@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
You also should use commands.has_permission()
Yes
nope
it works just fine with my alt
even with @commands.has_permission()
What is your py-cord Version?
latest
That is?
Can you try commands.Bot?
well that would mean i would have to change my entire code
from .command to .slash_command
anyways i doubt that would make any difference
ik
You have to change nothing
I have to change my whole code from @moderation.command to @moderation.slash_command
You still have to change nothing
Only discord.Bot to commands.Bot
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
You have to use a different name for each callback.
Can I wait for callback?
for example
for i in range(5):
button, interaction = view.wait_for_callback()
i++
Well off topic for codes but how do I start a new line in terminal like this?
try shift+ enter
Shift+Enter doesn't work
then try && rather pressing enter
how exactly?
set path=foo && set path=bar
Still cant btw
anybody want to help me in #1022887797629136926 ?
What's the fastest way to ping the command sender?
await ctx.respond(f"{discord.Message.author.mention}")
...ctx.author.mention, that won't work
it works for me...
discord.Message is a generic message object, it won't have an author
How would I make a bot remove a certain reaction after a certain amount of time
use remove_reaction instead of add_reaction after said time?
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```
yeah but how do i remove the reaction. i can't figure out the member thing
help pls
provide relevant code pls
Here
Help pls
Is there a way to check which guild a button interaction is made?
interaction.guild.id im not shure
Okie. Thank you :)
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction how do i solve this error
@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?
Help pls
you cannot have a option inside a option
probably invalid token
I was asking if we could change the option value/text based on the user who's running the cmd
no
kk
No
send code then
@fervent cradle
im pretty sure it is possible to make options based on what user is doing the command
well what's config ?
Oh please tell me how!
#998272089343668364 message
you cannot use choices=[] two times in one Option
Help
did i make that claim
?
?tag paste
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here is the error again
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
we can
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
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
you can wrap your code in a try/except block and catch systemexit error
try:
#code
except SystemExit:
pass
but how exactly do we get the ctx.author.id option outside of a async function (a command's function)
you can't get it outside of a command
exactly!
damn
helpppp
same error still
can you show me your code?
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?
its a button, all it does is exit()
async def regen_button_callback(self):
exit()```
self, button, interaction
oh and the callback is bad
do this in the command:
try:
exit()
except:
pass
i didnt change the name
wow
it doesnt give an error, but the bot is still on
@white wadi
exit() also works
no, he's trying to exit without an error
np
what do i do??
@fervent cradle Please don't cross post.
you cope, that's what you're gonna have to do until someone answers you
Choose either your help thread or this thread, not both.
oops
Next time it will be a warning.
alr
is there a way to get the user count of the bot without the member intent?
if you don't have the members intent any list of members from a guild will return [] iirc
so i cant even get the User object without the intent?
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 
you can still access ctx.author and interaction.user and stuff like that
but i only need the user count, without any events or commands 
ctx.author as Member object or User object?
anyone happens to know how to make ur own author_check in a paginator?
you can just pass in any function that returns True/False that takes an interaction argument
or i guess specifically set the paginator.usercheck attribute to it
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)
@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())
for i, item in enumerate(result):
if i == 20: break
embed.add_field(name="Test", value=item['line'], inline=False)
await ctx.channel.send(embed=embed)
bruh 🤣
you didnt define item....
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?
ctx.respond
You respond to interactions
instead of ctx.send?
if you use discord.Bot yes
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))```
i did that but i can't fix the problem
Literally read your add_view line and you'll see what's wrong
This is problem solving skills.
i don't know...
just add_view?
Add_view is a bot method
Congrats. You did it yourself.
thanks
do you have tips to learn that?
error handler?
a handler for what?
for make my commands
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)```
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!")```
It's missing a custom_id
does the custom id may be used several times, i.e. in different views?
each persistent view you add must have it's own custom_id
I also cannot be the same custom_id each button
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
hey, how can i check if a user is banned?
try:
entry = ctx.guild.fetch_ban(user.id)
await ctx.send("user in ban list")
except discord.NotFound:
await ctx.send("user not banned")
should something like this work?
it should just be user, not user id
hello guys, who can help with the question? how to get the name of the user who clicked on the button
ping please
interaction.user
I’m confused as to why it says I’m in the list
ok thx
¯_(ツ)_/¯
print entry and see what it prints
it’s fixed now :)
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
isn't it discord.ext.commands.Bot?
?tag replit
Read this to find out how you can install Pycord in Replit
Old instructions: https://web.archive.org/web/20211128084858/https://namantech.me/pycord/installation/#replit
New instructions: #998272089343668364 message
https://docs.pycord.dev/en/master/quickstart.html its pretty much from here
even if i do that it wont work
could you read the question once again "followed all the instructions inculdin disabling auto install"
trying to import it gives me ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) anyways
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
anyone know a fast way to check if a user is in any vc the bot can see?
ctx.voice_client
can channel.send can be ephemeral -ed? like private so only the one user can see it?
Nope
damn
Well, imagine this being abused so it floods your chat
How do I react to my own message? I tried await ctx.add_reaction("🤣") but it didn't work.
oh sorry i meant if i could check it outside of a command. is there anything for that?
ctx as in commands.Context or discord.ApplicationContext?
This is the command I'm trying to add it to```py
@bot.slash_command(description="test")
async def test(ctx):
await ctx.respond("test")
await ctx.add_reaction("🤣")
await ctx.message.add_reaction(*args)
Thanks
Is it possible to make the button work after the bot is restarted and it would not have to be sent again?
Here's the persistent example.
Thanks
thanks, i think that should work!
When I try to do py @bot.slash_command(description="test") async def test(ctx): await ctx.respond("test") await ctx.message.add_reaction("🤣") Then I get 'NoneType' object has no attribute 'add_reaction'
Am I missing something?
try
await ctx.respond("test")
message = await ctx.interaction.original_message()
await message.add_reaction(*args)
ok
Now I get 'Message.add_reaction' was never awaited
I made a typo so see updated code
ok
It worked. Thanks
are you able to use emojis in the placeholder for the select drop down? and if so how?
You can’t use external emojis in a select menu placeholder, no. But you can use default emojis (e.g. '🎉') in the label parameter of the select menu.
ahh oka, thanks!
np
wait just to clarify, i can use default emojis in the placeholder right?
Yes
i dont see in the docs where id set the label for the placeholder
ok i sort of got it, the emoji showing up but its not the discord version. is that normal?
How do I make a slash command with a space in it?
Yeah it's normal and there isn't anything you can do about it
It's just how Discord made it
damn
If you want everything to fit you can put a \ infront of the emoji to show the original so 💡 becomes \💡with \:bulb:
i believe in you can set the name property in the command to be the string with the space, like "command name"
good to know, but i think for now ill just live with it lol
I tried doing this py @bot.slash_command(name="test command", description="test") async def test_command(ctx): await ctx.respond("test") but I got Command names and options must follow the regex \"^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$\".
I just found out I need to make a slash command group for each word
ohhh ok, also good to know lol
Yeah
You have to make a slash command group
b!rtfm pyc SlashCommandGroup
@dire spade
Thank you
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)
ephemeral messages cannot be deleted
It’s .respond not send_response btw
ohh ok. idk why the other was working then
send_response isn’t a method of ctx or commands.Context.
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
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
how do you add options to a slash command in a cog?
you would use option or optionchoice
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
yeah i tried that and every time i start the bot it doesnt load the command
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
)
):
wrong option
"Option" not "option"
they are different
mid sending your full count code with "
```py
code here
```
"
^
its still not working
Why do I get "Converting to "Option" failed for parameter "command"." when using bridge ?
device_name: discord.Option(str, "(Optional) Name of the device", required=False)
yes
ok that worked. thanks!
no problem 
just want to draw attention back to thuis
whats your issue? mind posting your code with
```py
(code here)
```
.
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
whats the point of member?
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
reaction = await message.add_reaction(emoji)
await message.remove_reaction(emoji, reaction.author.id)
try this
also member isnt a valid intake of remove_reaction()
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()```
remove_reaction doesnt take "member"
AttributeError: 'NoneType' object has no attribute 'author'
@naive steppe
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'```
you're using discord.Bot which is the generic class, you need to use your own bot object
Bot = discord.Bot()
bot_owner = Bot.fetch_user(324152796414869506)
How to use @client.event if i run bot?bot.run()
bot.event?
basic python?
@bot.event
async def on_ready():
print("hbdj")
remove the ()
ah
at the event
sorry 🙂
not in a cog
in a cog ist @commands.Cog.listener()
do you know how to get the message id of a interaction response?
msg = the message
msg.id
i wanted to do that but that doesn't works:
msg = await interaction.channel.fetch_message(close_message.id)
await msg.delete()```
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
Oh other way round
?
Replace interaction with close_message
thanks!
AttributeError: module 'discord.bot' has no attribute 'event'
lol
discord.Bot()
how exactly would I implement this in my bot?
same like the other stuff?
Do u know how to fix this:
TypeError: Client.event() missing 1 required positional argument: 'coro'
@young bone
remove the ()
why discord.Bot.event???????
?
You said that
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}')
^
How should i create my own object? is Bot = discord.Bot() enough? i have it inside the main file, this file with this code is a cog
if you're using cogs, you have self.bot defined no?
oh sh*t, i forgot
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()
no like which class do i get it from
I'm new to pycord sorry
so ctx.channel.is_nsfw() returns true / false
example:
channel = Bot.fetch_channel(id)
print(channel.is_nsfw())
Help plz
could I similarly get Bot.fetch_author(id) ?
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```
help pls
Fetch the author of what?
You prolly mean messages
the slash interaction
I figured it out by reading docs, thanks for helping out :D
pls
class Ticket(commands.Cog, name='ticket'):
def __init__(self, bot):
self.bot = bot
same error
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")````
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
doesn't help too 😦
Did you import sys and traceback?
yes
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```
help
that's not a cog. that's a view
Let me try using the txt file you gave
ok
that says view
the slash command is defined with the MyView class
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
@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!")
what's the problem?
Change your add user command to that.
done.
Try now because it works for me.
@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.
ah
so it needs to be in a command/event?
yea
you can put it in __init__
also get_channel takes an int, not a string
ok
can i ask you something else?
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)````
you should probably just copy and paste ticket_perms into your OpenTicketView file
simplest solution I can think of that won't overcomplicate things
hopefully.
i did that but my code look dies
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
the autocomplete may take too long
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
@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
so now there is an other problem
i wanted to import the channel but it gets an error
I fix problem, bots don't have event
It's imposible add event to bot
They can only listen
what version was bridge commands added to pycord?
2.0
specifically which b version
Show your pip freeze
verifikation_view = View(verifikation_button) throws this error : TypeError: View.init() takes 1 positional argument but 2 were given
how do I edit a .respond() message? for example, im using:
await ctx.respond("test")
so how do I edit that message?
tysm
Why?
Can you show the pip list
I fixed it, but now comes
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
Show your pip freeze
How?
Open your terminal and run pip freeze
Pycharm has a Python Packages button on the bottom. Click and screenshot
pycharm uses venv so it wouldn't be the same anyways
remove discord, discord.py, and add py-cord
How i can install py-cord
click add package
But i need a git
actually click "Search for more packages" and type py-cord
and click enter
Thx, its works.
yw
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'
Posting it 5 times for what
it was only 2 iirc
@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?
How can my bot send a webhook? (As embed)
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
for an autocomplete function, what parameters does it take? ctx and interaction?
requests is "blocking" in a way. i'm not sure how to explain it thoroughly but it blocks other functions/commands from being ran. its recommended to use aiohttp which is already installed with pycord.
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]```
@rare ice
oh ok just ctx, thanks
?
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
Without a command? How exactly then? An event? A task?
like i want to just write and have it execute
not write then go run a slash command
get the channel object and useawait channel.send()
you can get a channel object with guild.get_channel(id) or await guild.fetch_channel(id)
ty
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))
nice webhook url
F
can you delete it pls
Why?
and dont show the webhook url
remove the webhook url from code
Its a test webhook and a test server xD
"embeds=webhook"
No
No what lmao
Dont work
It's your own code. I'm remarking your error
Its dont work
Nice help. 👍 (irony)
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.
What do I have to write for it then?
Actual embed objects?...
I have it already but it dont work anyway await embed.send(embeds=embed)
Yes
Then?
You'd know this makes no sense.
await webhook.send(webhooks=webhook)
?
You definitely don't know how this works.
Right
webhook.send is the same as ctx.send or channel.send or ctx.respond
The embeds kwarg takes a LIST of EMBED OBJECTS that you provide
how can i get an channel in a view class?
(i wanna send a message in a other channel)
So what do I have to write down?
You could use
channel = discord.utils.get(interaction.guild.channels, id=1985892939)```
Or iirc interaction.guild has a get_channel method. Don't quote me on that
More features to make your bot cool and snazzy.
thanks
don't expose your webhook url
just realised the send embed with some text doesnt include the text
await ctx.respond("<@user.mention> Welcome.", webhooks=webhook)
At this point. I'll just assume you don't even know python.
Test URL, Test Server, Test Channel
Lol. Didn't notice.
Just say it and don't beat around the bush here. i want to learn it.
yeah but spoonfeeding isnt learning
What he said
Yes I know. but I want to get this done.
You're just impatient and not reading your own code.
Not how programming works sadly.
just say it please
go off this logic
Per https://docs.pycord.dev/en/master/api.html?highlight=webhook send#discord.Webhook.send in the parameters.
Now its this
Yup, you messed up again. Show your code.
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))
webhooks dont have anything to 'respond' to
Than send?
try and see
python is not for beginners. If you try using py-cord as a beginner, you will struggle.
There's no webhook object lmao
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
is already fixed in my code
So what should I write in the line?
Please tell me, I want to read this tomorrow, but the code should be ready today.
do you even understand what the code in your banner mean?
Listen. Not tryna be a bad person, but this is basic python.
Variables are the most basic python
.
#998272089343668364 message
My English is bad
the picture is all u need
*example
What
yeah bruh
Girl. I'm not the one that needs help
your english is shockingly worse than my code
still better than my js
I don't think they know what the code in their banner does
Your'erue'r*
Cant believe people still mix up your and your'erue'r in 2022 smh
i think someone off da perc
Anyone knows how i would go about creating a command which would fetch all users with a certain tag, something like dyno has "/discrim"?
Go over your users cache
does message.edit() only change the things i pass into it or the whole message?
only what you pass
so when i have a message with an embed and i dont pass the embed in edit() my embed stays right?
yes
thanks!
whats the difference between these two?
obj = discord.Embed(title="bla")
obj1 = obj
obj1 = obj.copy()
Is there a limit on how many tags a forum channel can have?
obj1 will only point to obj so editing obj1 or obj will edit both. using obj,copy() will create a new instance with same stuff as obj but editing one will not edit the other. Think of it as an interactive whiteboard and you drawing what they drew on your whiteboard and only you can draw it
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 ?
you can't attach views to embeds
they attach to the entire message
Ah shucks I see, hmmmmm.
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))
is there a way to have the bot not display the attachments URL?
Either use an embed or use file=discord.File(path_to_file)
make it into an embed =)
like you'd call a regular function? i'm not seeing what you're trying to accomplish here
how to use .edit whit message_id ?
if it's your bots' message your bot will always have access to it
thanks <3
If it doesn't recognize me, the get_message works the same, doesn't it?
if you have message caching turned on
yes
are you using py-cord 2?
I think not, I haven't updated it for a long time.
pip list in terminal and show stdout
what would be the command line to update? pip upgrade pycord?
?tag install
- 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
2b
you can use the discord.py support server for discord.py inquiries
there I changed it again, I can't believe I use another library xd
so you are using py-cord?
you uninstall discord.py, right?
yes
I don't see the error because I have a try except :'v
remove the try except
what is the message
so your bot sent the message?
if the bot sends the message a long time ago, but does not edit it.
if it was sent before this current session. It wouldn't be cached
would I have to send the message and then edit it? like new
you can use
guild = await bot.fetch_guild(guild_id)
message = await guild.fetch_message(message_id)
await message.edit()
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?
wdym
I don't know the abbreviations in English xd
Does message.content naturally not register inside of a class?
Intents are set globally
and it works outside of the class just fine
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
Hello! How do I make a command alias?
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)
on_ready
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
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
You set them in the command.Bot(activity=activity) activity needs to be defined beforehand though
it should be defined just as you would define it in on_ready
No, it's a very inefficient way of doing it
u mean reactions?
A countdown with reactions yess
hm
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
yes, last I will do something simple with text.
I doubt this is even possible
my other cogs are working and this is the only one causing trouble
remove the add_command line, you don't need it
you have a line in your cog that's doing bot.add_command
its add_cog
show the file
there
can you also paste the full error
k
oh you're using the wrong type of bot probably
nope needs to be commands.Bot from discord.ext.commands
Then how do i use discord.Bot
you don't, if you want prefix commands you use commands.Bot
which inherits from discord.Bot
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
Here's the slash autocomplete example.
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
do you have something else installed?
what
show the pip list
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
indeed, this is a known 2.1.3 issue
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
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
wdym refuses to work. what happens
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
Is the bot online ?
yep
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')```
where’s your application command code for the command that you "can’t see?"
/ping should be, according to the example
(sorry if it sounds super dumb am still new to the api stuff)
Might be that u are using prefixed commands, not slash commands
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
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
why do you use both client and bot
gotcha, thanks
and no slash commands are near instant now
mine are lol
the reason your commands dont work is because you're using both client and bot, of which only client is run by your token
ahhh, so I should run both?
ah got it, thanks
yeah I just left the prefixed but didn't understand it would interfere with the slash ones
not after backend v2
global commands are registered just as fast as guild commands.
ah ok got it
I'm consistently getting 404 interaction not found with this slash command: https://github.com/thefightagainstmalware/Spectamus/blob/64eae364c7035b7e966d774774b44f53e7995106/bot.py#L43
bot.py line 43
@client.slash_command(debug_guilds=[910733698452815912])```
I had a similar issue. Try to defer.
In my case the bot was taking too much to respond.
how can i check user's roles after slash command execution?
ctx.author.roles is a list of roles
thanks
Really anything with DB usage should defer as a general rule.
DBs can take a bit to respond.
i see
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
@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'
learn basic python
i tried to code something like that its my first time
bro please lmao
bro u wanna see shit i coded
ik basic python
j havent done something like this
so it got me messed up
this example should help - https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_basic.py#L34-L38
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)}")```
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}")
Extension 'cogs.Ticket' raised an error: NameError: name 'ticketID' is not defined
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
So how do I enter the variable data into the button id. It swears
if you define it you dont need the f"{}"
so it will just enter the name of the variable, and not the data that I need
@discord.ui.button(emoji=':Trash:', label='Удалить тикет', style=discord.ButtonStyle.gray, custom_id={ticketID2})
I'm stupid I don't understand
you also should take a look at basic python
why can't you just do this and that's it custom_id=f"{ticketID}"
it ultimately depends on the context of your code, that's just how python is
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 
okay
thanks
Is it possible to subclass the context? If it is, is there a guide on doing that?
Here's the custom context example.
@proud pagoda ^
Thanks
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?
nvm, it works now idk what i did but it works
Quick question - can select menus be added to modals? The docs say that modals only accept InputTexts
I'm sure it's not a feature yet
Yeah I wasn't totally certain but for some reason I misremembered seeing them in modals before
they were unofficially, but they were removed because they were unstable
I see, that explains it
how can i get the bot user count?
bot.users but only with members intenet
yes

