#General Help
1 messages ยท Page 8 of 1
how did you add that ping command
different cog 
and that cog would load a new command fine?
there's only 1 command there and I didn't touch that cog for like 4 months 
might as well try
didn't work
Is there something I need to do for the values to not stay 'selected' after I select them. I select orange and everything runs fine but the orange value just stays there. It's more of a visual thing, but also since the orange value remains selected there, I have to select another value before I can reselect Orange.
Also I don't specify max_values only min_values=1 but it automatically takes it as my selection not letting me select more as if I had also set max_values as 1
min, max=1 is the default https://docs.pycord.dev/en/master/api.html#select
this is a client thing so you can't override it unless
- the user reloads their client
- you edit over the message with a new view
so when I defer inside a modal's callback, it sends a response message:
async def callback(self, interaction: Interaction):
await interaction.response.defer()
if I don't defer, I get an "this interaction failed". What can I do about it? I don't want to send a message when I defer()
you still need
interaction.response.send_message(message)
that's a discord design?
thats how you send messages with it
but I don't want to send any message after that
but if I don't, I get "interaction failed"
that's the issue
nope
with slash commands when I do defer() it doesn't send a message
that's happening only with modals
defer is only used for extending the response time
even if you defer in a slash command, you still have to respond
the same goes for all interactions on discord
but why on modals it sends a message automatically?
it doesn't, that's the response body
the same happens when you type a slash command
you'll see a little "thinking" prompt
I don't get it.. i've been using defer on all my slash and that's not happening
there is no "thinking" prompt
and theres no "interaction failed"
because your commands are executing very quickly
maybe "interaction failed" comes after a while, but stil no thinking prompty
i'm not sending messages on my views, I'm mostly editing the already sent message
oh not thinking, it'll be sending command
that may be considered a response
well on my modals I'm also doing the same thing
but there is a thinking prompt
couldn't it be a bug with pycord?
i just tested and you can submit fine without it
do interaction.response.edit_message
regardless, every interaction on discord; slash commands, user commands, buttons, dropdowns, modal submissions, etc. requires a response that's either sending a new message via response or editing the message that triggered it
yeah, that worked, thank you
all good
still weird that defer() is working differently when used on modal's callbacks
well, I did defer because even using interaction.message.editI was getting "interaction failed"
so I guess it wasn't counting as a response
defer is only needed if your response takes more than 3 seconds
anyways, may I ask you another thing?
sure
whenever I send a modal after another modal has been submitted, the placeholder value is the value from the previous modal
is that a discord design?
now that's weird
sounds like you're crossing variables somewhere
well I'll re read my code later
what does this code do?
def __init__(self, channel):
super().__init__()
self.channel = channel
Hi. How do more than 1 dropdown, to one message? Can I do this?
you can pass arguments.
after a button has been used how do you disable thee other buttons in that view for that channel
No results found when searching for disable_all_items in pyc
thanks
do you have a use case example for disable_all_items
Any slash command in a cog examples?
How do i convert Users to Member objects ?
users as in? An ID?
yes
b!rtfm pyc get_member
Or
discord.utils.get(ctx.guild.members, id=124558)```
ive been trying to get get_member to work and it keeps giving errors
ctx.guild.get_member()
keep getting interaction failed for disabeling the buttons
its just returning none
Then the user is not a server member
its my id tho ?
Try this
thats also retuning none
Hi guys, I'm trying to use embeds, but I'm running into this issue
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Embed.add_field() got an unexpected keyword argument 'title'
This is my code
embed = discord.Embed(
title="My Amazing Embed",
description="Embeds are super easy, barely an inconvenience.",
color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from
)
embed.add_field(title="A Normal Field", value="A really nice field with some information. **The description as well as the fields support markdown!**")
embed.add_field(title="Inline Field 1", value="Inline Field 1", inline=True)
embed.add_field(title="Inline Field 2", value="Inline Field 2", inline=True)
embed.add_field(title="Inline Field 3", value="Inline Field 3", inline=True)
embed.set_footer(text="Footer! No markdown here.") # footers can have icons too
embed.set_author(name="Pycord Team", icon="https://example.com/link-to-my-image.png")
embed.set_thumbnail(url="https://example.com/link-to-my-thumbnail.png")
embed.set_image(url="https://example.com/link-to-my-banner.png")
await ctx.respond("Hello! Here's a cool embed.", embed=embed, ephemeral=True) # Send the embed with some text
It's from a Pycord guide and I think either the syntax got updated and this guide is outdated or I am doing something wrong
Do you have intents
fields don't have the title argument. It's name
Ohhhhhh was this updated
Nope, it has always been like this as far as I know.
Is this guide outdated ๐
Huhhh ok i see
I got this example template from here https://guide.pycord.dev/getting-started/more-features/
More features to make your bot cool and snazzy.
Uh so i have been trying to update my ban command and it works fine as a slash command but when I try to use it as a prefix command it fails.
I have narrowed the error down to banning a member outside the server.
This does not work with either users in the server or outside:
@commands.command()
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
user = await self.bot.get_or_fetch_user(member.id)
await ctx.guild.ban(user=user, delete_message_days=0, reason=reason)
This works with both users inside and outside the server but does not work with @mentions:
@commands.command()
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member, *, reason=None):
user = await self.bot.get_or_fetch_user(member)
await ctx.guild.ban(user=user, delete_message_days=0, reason=reason)
Working slash command for reference:
@moderator.command(description='Ban a member from this server!')
async def ban(self, ctx, member: Option(discord.Member, description="@mention or user id of the member you wantto ban", required=True), *, reason=None):
await ctx.guild.ban(user=user, delete_message_days=0, reason=reason)
```
I need to get the data of the message my pycord bot has been called in form of a reaction.
Earlier, this used to work ctx.channel.fetch_message(ctx.message.reference.message_id) but cant find its replacement in pycord. Any help here.
Just check if member is a Discord.Member object or an int.
Wdym in a form of a reaction
in the first example?
Mhm.
like I am replying to this message, assuming I am the bot, I need 'Wdym in a form of a reaction' with me.
Can anyone help me in making a slash command that works as a response to a message?
you can't reply to messages with slash commands
I know that but can I call a slash command in form of a reply?
not... really?
a slash command response is technically a reply to yourself
well not technically, it just looks like it
all good
how would I send a modal on button_callback (when button is clicked)
how to set a value and description for each auto complete option?
I believe you can return a list of OptionChoice objects which have these attrs
I used on_interaction to grant the role when the button is pressed, is there any other better way?
I don't want to change the message after restarting.
It is exactly what I was looking for! Thank you.
has anybody worked with mongo here?
my bot is catching events like on_message but its not responding to commands
could there any possible reasons for that ?
ok i try and thank
what's wrong with getting a variable like this?
Whats the max time for the delete_after arg?
doesn't seem to have description oof
choices dont have descriptions
if you mean an autocomplete description just use the option description
I was saying auto complete there lmao
Wdym option description?
Option(description="...")
I didnt think you would ask this
So like ```py
return [discord.Option(name=thing, etx)]
U told me to use that
you cant return an option
you can return OptionChoices
Kinda confuse
and those dont have descriptions
Which example shud I look at?
where do you want the description to go?
where should it be written
Nvm forgotten how autocomplete works
Ok
So return discord.OptionChoices
For auto complete
Ok
Sorry forgotten that autocomplete cannot have description like the args for slash cmds
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\cog.py", line 723, in _load_from_module_spec
setup(self)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Verify.py", line 95, in setup
bot.add_command(verify(bot))
AttributeError: 'Bot' object has no attribute 'add_command'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\main.py", line 19, in <module>
bot.load_extension(f"extensions.{filename[:-3]}")
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\cog.py", line 783, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\cog.py", line 728, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'extensions.Verify' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
Why can i not use normal commands in cog?
anyone understand this error?
reinstall package
The default_permissions decorator isn't working on my bot. It doesn't matter if I set it or not, the command can always be invoked by all members.
This is my code:
@message_group.command(
usage="<channel> <message>",
description="Sends a message in the given channel.",
)
@commands.guild_only()
@discord.default_permissions(embed_links=True)
async def send(
self,
ctx: discord.ApplicationContext,
channel: discord.TextChannel,
*,
message: str,
):
await channel.send(message)
await ctx.respond(
f"Successfully sent the message into {channel.mention}.",
ephemeral=True,
)
Am I doing something wrong? Well, probably yes, but what?
how to just delete the message with button if the button was not clicked under 7 seconds
what about await channel.send(content, view=view, delete_after=7)?
just delete the message after 7 seconds using the delete_after argument
well, there is pblm, the message gets editted after pressing button and i dont want the editted message to get deleted
coz editted message will also then deleted after 7 secs
hm
my bot isn't reading message.content is there a reason for this? its only reading when i @ my bot
?tag 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)
.
chill, i'm thinking
set the view timeout to 7 seconds and override on_timeout
did that but, timeout function is still being called after i press the button
after 7 sec of pressing
then just check if the button was pressed inside on_timeout
worked, thanks. was wondering why it wasn't working, cause on discord.py it worked ๐
i mean it can't be that hard to think of how to check that
also is this expected behaviour of timout func?
yes, timeout is always called when the view times out
pressing the button doesn't stop the view
uhmm should i just do view.stop in callback function?
well you can but that'll still call on_timeout
brrr
just make another variable that checks if the button was pressed
thought of dat, but not sure whether the variable might be mixed when the concurrency is increased
coz i am suffering with similar issue, see this #976001050110726245
it shouldn't mix, but if you're worried about that then map to an ID inside a dict or something
so just rewritting whole part of this
ok lemme try with variable
Can someone help me?
can the discord.commands.Option be subclassed and have a some sort of Context?
what's the use case?
I need to access the user's, who invoked the command, id
I also need to get the discord.Bot instance
but I think I can access it, because the subclassed Option is in a cog
so I only need the user's id
wait, how do I get the discord.Bot instance if it's a class inside a class?
is it necessary to close a file after i open it in python?
not necessarily but closing them frees memory for python to use
generally you should use context managers to handle opening files and such
One message removed from a suspended account.
Hi, do message.content still usable in the 2.0.0rc1 version?
I had this same issue, now it's fixed, thank you
hey
i want the bot pick up one random option of the list below
random = ["option1","option2","option3"]
this is the list
help
i forgor
use random.choice (also don't call your list random)
Ignoring exception in modal <extensions.Verify.verfiy_modal object at 0x000001BDB87CE550>:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
await value.callback(interaction)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Verify.py", line 71, in callback
await channel.send("Test")
AttributeError: 'NoneType' object has no attribute 'send'
your get_channel returned none
how can i fix that?
do i have to import any library?
channel = bot.get_channel(id)
await channel.send("Test")
(in cog with modal)
self.bot.get_channel() have i tried but not working..
random
is id an int
so?
channel = bot.get_channel(int(939551193145950258))
when yeah is dont working
hi why is that when i install pycord with python3 -m pip install -U py-cord --pre and start my bot it says no module named 'discord_components'?
I wrote my bot using pycord and it's been running great for the past months. Now that I moved the bot to another server it's not working.
k
Can someone explain this traceback to me? Its happening after exactly one command execution.
Ignoring exception in command settings music:
Traceback (most recent call last):
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 762, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Workspaces\tornado-bot\cogs\settings.py", line 33, in music
await ctx.defer(ephemeral=True)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 494, in defer
await adapter.create_interaction_response(
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 211, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
await ctx.command.invoke(ctx)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
await injected(ctx)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 1020, in _invoke
await command.invoke(ctx)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
await injected(ctx)
File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
It is possible to do some task like closing connection to a db when the bot is stopped?
do you want to show your code?
settings = SlashCommandGroup("settings", "Change the bots settings on this server.",
permissions=[CommandPermission("manage_guild", 2, True)])
@settings.command()
async def music(self, ctx: ApplicationContext,
option: Option(str, "Select an option.", choices=["embed size: [Small | Medium | Large]",
"delete embed when finished: [True | False]"],
required=True), value: Option(str, "Select a value.", required=True)):
"""Configure the music player."""
# await ctx.defer(ephemeral=True)
if not values_valid(option, value.lower()):
await ctx.respond(f"โ **{value} is not valid** for {option.split(': ')[0]}.\n"
"๐ **Valid options are** shown **in the brackets** behind the option.", ephemeral=True)
return
options = {"embed size": """UPDATE settings SET MusicEmbedSize = (?) WHERE GuildID = ?""",
"delete embed when finished": """UPDATE settings SET MusicDeleteEmbedAfterSong = (?)
WHERE GuildID = ?"""}
values = {"embed size": {"large": 2, "medium": 1, "small": 0},
"delete embed when finished": {"true": 1, "false": 0}}
value = value.lower()
option = option.split(": ")[0]
cur = database.cursor()
cur.execute(options[option], (values[option][value], ctx.guild_id))
await ctx.respond(f"โ
**{option}** has been **set to {value}**.")
The command works perfect the first time, the second time it does not
and raises the error in the traceback
and what does it say from the client side
what do you mean?
can someone help me?
I had a hidden python interpreter running completely invisible in the background without a reason. Fixed it, thanks
You got an answer "your get_channel returned none"
yeah and how can i fix that?
I haven't received any replyI haven't received any reply
how would you use disable_all_items for a interaction?
I'd do py discord.utils.get(ctx.guild.channels, id=idHere)
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 1147, in on_connect
await self.sync_commands()
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 643, in sync_commands
Traceback (most recent call last):
File "main.py", line 2, in <module>
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 1147, in on_connect
await self.sync_commands()
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 643, in sync_commands
registered_guild_commands[guild_id] = await self.register_commands(
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 473, in register_commands
prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id)
File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
why am i getting this error every time i run the bot?
because some server hasnt granted the bot access to the applications.commands scope
umm
how do i fix this
i toggled it on when i made the invite link
servers have to reinvite with the appropriate scopes turned on
Thanks
Hi, I am trying to add a command with custom permissions. For this I am using this line:
@self.slash_command(name='test2', permissions=[discord.CommandPermission(id=ROLES['Slash'], type=1, permission=True, guild_id=GUILDS['Bot Development'])])``` however the permissions don't get set correctly. What am I doing wrong?
CommandPermission has been removed due to the shift to v2; it doesn't exist on rc1 and beyond
you can no longer set user/role discord-level permissions via the bot, you can only do that via the server's integrations tab now
if you still need to limits commands to bot owner, you can just use checks instead
Huh, that's sad. But thanks for the answer!
youre not out of hope
I mean, I was looking for elegant solutions, I don't think checks will do the job? (Although I don't quite know how they work yet, so I will see)
they will
some basic checks can be found in the commands extension
they raise errors if the check doesnt pass for your error handler to handle
But the commands would still show up if users type '/' in the chat, which is what I wanted to avoid in the first place.
rq, before i obliterate my bot, do i need to call await interaction.original_message() before accessing interaction.message.id, or do i have to do message = await interaction.original_message()
which you cannot do
if the users cant use a command then i call it good enough
if you really want no one else to see your command, either manage it yourself via the integrations menu or limit it to your own guild if that isn't an option
not necessarily, but if interaction.message returns None then yes
in my experience interaction.message has worked pretty reliably but it might depend on other factors
thanks
Not directly related to pycord but more of a general question. I currently have the following code:
async def request(self,
*,
method: callable | str,
endpoint: str,
data: dict = None
) -> dict:
I'm currently getting the following error in relation to the method argument: TypeError: unsupported operand type(s) for |: 'builtin_function_or_method' and 'type'
Anyone know of a good way to get around this? For reference, the method param should either take in a string like "get" or take in a callable such as aiohttp.ClientSession.get.
what python version are you using?
3.10.1
huh, that should work then
if not then the workaround is to import Union from typing and use that instead
yeah, weirdly enough that fixed it. isn't the | operator in type hinting in python 3.10 meant to replace typing.Union?
yep, but its the simplest work around i see right now
So idk if i understand that correctly. If i run my bot then change a cog (while the bot runs) then reload that cog with reload_extension, the changes i made should update right? So the next time when i use a slash command it should have the updated behavior. Or did i missunderstand the use of reload_extension?
its intended use is to change functionality while the bot is running
that's meant to be the case but slash callbacks are weird with reloading so idk if it works
Oh ok. Bcs i reload my cog and the slash command has the old behavior.
iirc it was meant to be implemented properly but it hasn't worked in my experience
because you have to sync them
hey, somehow nothing works for me anymore, I uninstalled everything and then couldn't install anything in the terminal, do you know what's going on there?
with sync_commands?
yes
looks like using typing.Callable instead of the builtin callable also works, any idea if this could maybe be intended behavior or a bug?
mh so i tried using sync_commands after the reload already, same results no error.
ยฏ_(ใ)_/ยฏ
So i now tried to only unload a extension. But when i unload a cog the slash_commands where still available and functional. No error. Im confused.
what version are you on
just tried and on rc1 it looks like reload_extension alone works for me now
which is nice to know
2.0.0b4
jesus
uhh i recommend updating to rc1
though do note if you specified the messages intent, you need to change that to message_content
Jup thanks. Myb should update more regularly
e: The unload still doesnt work ig. But idc wasted to much time on this.
you need both for prefixed commands
Can I fetch a user by their username and discrim?
In a guild or global?
global is not possible as far as I know
Hi whether it is possible to transfer arguments to model?
Ah. In a guild?
You're not passing those arguments.
try this:
from discord.ext import commands
user = await commands.UserConverter().convert(ctx, "user#1234")
else look here https://www.reddit.com/r/Discord_Bots/comments/g0eoqj/is_it_possible_to_get_a_users_id_just_from_their/
or use google ๐
7 votes and 6 comments so far on Reddit
I just see, that would actually be a command
Ah. Thanks.
actually this is far simpler I think
member = discord.utils.get(message.guild.members, name='Foo', discriminator='1234')
Yeah haha.
I'm trying to have a group of commands that any user can use, but I would like them not to be used at the same time.
Is there any way to set a "shared" cooldown or what should i look into start/stopping users from using commands
@commands.cooldown(rate, per, commands.BucketType.<type>)
<type> can be channel, guild, user/member, category, role

How do I fix this error with mongodb?
dude, why posting it here if you already have a thread for it...
Because no one answers in threads
or maybe people just havent responded yet ๐คจ
lmao
Is it possible to get the value of each row of a long modal text input?
what arguments are available in await respond? i tried ephemeral=True and got an error
https://docs.pycord.dev/en/master/api.html#discord.InteractionResponse.send_message is called if you haven't responded yet, https://docs.pycord.dev/en/master/api.html#discord.Webhook.send is called if you have already responded
using the ephemeral parameter shouldn't be an issue with the function itself.
does interaction work with views only or slash commands too
like having an interaction object?
yup
slash commands have ApplicationContext which has a property of interaction
I see, thank you very much
Like this?
What @commands. Checks hide/grey-out the slash command?
How do i get the user that invoked the command? is there something like ctx.author?
yes
Hey i have two questions, i have a code for online members i have len(user) used for count but dont working.
Code:
for user in ctx.guild.members:
if user.status != discord.Status.offline:
print(user)
So my next question is, how i can see record of server boosts?
p.tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
second question, don't believe you can see a record
not?
what
can i see the record of server boosts, yes or no?
and this is not helping me..
i want only a answer for this
I said no, I don't think you can see server boosts
i lost power so you'll need to check for yourself tbh
and I can't help you with your first issue if you don't tell me what the actual issue is with the code
saying it doesn't work doesn't tell me anything
not problem, i want only a count to this
what exactly are you trying to accomplish. are you wanting to count the amount of online members?
just increment an int every time a member isn't offline?
count = 0
for user in ctx.guild.members:
if user.status != discord.Status.offline:
count += 1
should work if I'm understanding what you want
and print(user) for the count or?
not sure why you would print the user if you're just trying to count how many are online
wait
so i want a count this called example 239 Members is on the Server but only 23 Members is online so i want a count the bot target me the count gived also the bot target print 23
you know? im sorry my english not so good
still not entirely sure what you want, but if you just wanna print the amount of users online then place a print(count) after and outside of the for loop
I am i know what i want
But print 1, 2, 3, 4, 5, 6, ... i want but only number not 1, 2, 3, 4, 5, 6, 7 ...
so direct expamle 23
so basically this atmo bot i gave him founder everything with admin permission but he dosent even reply in the server and in dm he replies
enable message_content intent
ok wait
enabled but no work
How would I be able to get the user on who a UserCommand is used? For example I want to kick someone, I can right click them to get a user context menu, but how would I know who has been clicked?
For dislash it used to be ctx.target_author
Any ideas why the "get" seems to fail roleID ends up equaling the name=role value
async def create(ctx, role: Option(str, "role", required=True), colors: Option(str, "color", required=False)):
await ctx.guild.create_role(name=role, color=colors, reason=f'created by {ctx.author.name}')
roleID = discord.utils.get(ctx.guild.roles, name=role)
print('role id', roleID)
If i try to use Int(roleID) i get an error like
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Role'
roleID returns a Role object, so you'll have to use roleID.id to get its ID (which would already be an integer then)
๐
code was working fine a bit ago then it went ๐ฉ lmao
@ornate spade please help
I told you the idea I had
Is there a way to see the errors after adding cogs?
Like before adding cogs I could see errors in my terminal to do with commands and it was so much easier to fix them but now after adding cogs there are no errors in my terminal. So is there a way I can see them?
you also need the messages intent for the bot to receive messages that dont involve it for prefixed commands to work
done
Can I somehow respond to a Modal interaction without sending a message? My code right now looks something like this
class TestModal(discord.ui.Modal):
def __init__(self, title):
super().__init__(title)
self.add_item(discord.ui.InputText(label='Input', placeholder='Placeholder'))
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message('HI')``` however I do wish to respond there without the "HI" appearing.
you could try your luck with response.pong()
some people have had success with it
@plain rover
I tried
async def callback(self, interaction: discord.Interaction):
await interaction.response.pong() ```
However that doesn't seem to do anything.
my suggestion would be make that 'Hi' message into .send_message('Hi', ephemeral=True) so only Modal user sees it
Ooh, I didn't know this existed. Thanks!
why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd
Hey i have this error when i run the .bal command
I excepted it to make me a new balance account but i have this error
The code:
@bot.command()
async def bal(ctx,user):
await open_account(ctx.author)
users = get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)["wallet"]]
bank_amt = users[str(user.id)["bank"]]
em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
em.addfield(name = "Wallet Balance",value = wallet_amt)
em.addfield(name = "Bank Balance",value = bank_amt)
await ctx.reply(embed = em)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)["wallet"]] = 0
users[str(user.id)["bank"]] = 0
with open("wallets.json""w") as f:
json.dump(users,f)
async def get_bank_data():
with open("wallets.json","r") as f:
users = json.load(f)
return users
The error message:
Ignoring exception in command bal:
Traceback (most recent call last):
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
When i run the .bal command it does nothing
wdym?
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
what do i need to do?
provide input
i have the code provided above
@bot.command()
async def bal(ctx,user):
await open_account(ctx.author)
users = get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)["wallet"]]
bank_amt = users[str(user.id)["bank"]]
em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
em.addfield(name = "Wallet Balance",value = wallet_amt)
em.addfield(name = "Bank Balance",value = bank_amt)
await ctx.reply(embed = em)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)["wallet"]] = 0
users[str(user.id)["bank"]] = 0
with open("wallets.json""w") as f:
json.dump(users,f)
async def get_bank_data():
with open("wallets.json","r") as f:
users = json.load(f)
return users
thats the code
?tag codeblock
No tag codeblocks found.
oops
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
@bot.command()
async def bal(ctx,user):
await open_account(ctx.author)
users = get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)["wallet"]]
bank_amt = users[str(user.id)["bank"]]
em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
em.addfield(name = "Wallet Balance",value = wallet_amt)
em.addfield(name = "Bank Balance",value = bank_amt)
await ctx.reply(embed = em)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)["wallet"]] = 0
users[str(user.id)["bank"]] = 0
with open("wallets.json""w") as f:
json.dump(users,f)
async def get_bank_data():
with open("wallets.json","r") as f:
users = json.load(f)
return users
i just want to do .bal and when you dont have account it creates one and when you have an account to show your bank and wallet balance
so user is supposed to be an optional arg
i think so
user = None in function definition
what function?
then you need to set user to ctx.author if user is None
command
fyi dont use json as permanent database solution
yes but you might wanna use a different comparison operator in the condition
infact you shouldnt be using a comparison operator in there
what?
is None is what you need
why are u overcomplicating? just use:
user = user or ctx.author
if user is None?
yes or the above
Why this code send the cooldown embed(message) 10 times or more ?
class Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._cd = commands.CooldownMapping.from_cooldown(1, 6.0, commands.BucketType.user)
def get_ratelimit(self, message: discord.Message) -> typing.Optional[int]:
bucket = self._cd.get_bucket(message)
return bucket.update_rate_limit()
@commands.Cog.listener()
async def on_message(self, msg: discord.Message):
if isinstance(msg.channel, discord.DMChannel):
ratelimit = self.get_ratelimit(msg)
if ratelimit is None:
# not ratelimited (No Cooldown)
else:
# is ratelimited (Cooldown) embed```
error still gets sent to global error handler
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
got this error
user=None
you didnt make the argument optional
in function params
ohso and how do I prevent this
after doing user = user or ctx.author
Do I have to do ctx there ?
has nothing to do with your issue probably
right there
you want the user argument to be optional for the command to work
check if author is a bot then return
because bot is looping on its own messages
at bal or open_account???????
if you make user optional on the latter, it still wouldnt work without it
async def bal(ctx, user=None)
How do I optional write there in the parameter?
.
if msg.author == self.bot.user:
return
he's talking to @jolly belfry
im not talking to you
Ah ok sry
different error this time
show
wait
But my code didn't still work
Ignoring exception in command bal:
Traceback (most recent call last):
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 98, in bal
await open_account(user)
File "main.py", line 112, in open_account
if str(user.id) in users:
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
youre not ensuring that user is not None before the function
if message.author.bot: return
show your code
And where should I do that so under where?
above but lemme resend
move this to be before you call the function
under on_message
@bot.command()
async def bal(ctx,user=None):
await open_account(user)
users = get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)["wallet"]]
bank_amt = users[str(user.id)["bank"]]
em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
em.addfield(name = "Wallet Balance",value = wallet_amt)
em.addfield(name = "Bank Balance",value = bank_amt)
await ctx.reply(embed = em)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)["wallet"]] = 0
users[str(user.id)["bank"]] = 0
with open("wallets.json""w") as f:
json.dump(users,f)
async def get_bank_data():
with open("wallets.json","r") as f:
users = json.load(f)
return users
ok
wdym?where?
lemme do that
It works thanks
np
error again
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 100, in bal
await open_account(user)
File "main.py", line 117, in open_account
users[str(user.id)["wallet"]] = 0
TypeError: string indices must be integers
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers
why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd
move the ["wallet"] to the right outside of the square brackets
Don't use json as db
true
^ not as a permanent solution
what do i use then?
i feel data loss
i followed code with swastik tutorial
u can use my sqlite wrapper for creating economy easier
Discord.py extension to create economy easily. Contribute to Nohet/DiscordEconomy development by creating an account on GitHub.
hmm code with swastic hmm
json is not recommended but
i use mongodb altas
mongodb is better compared to just plain json files
ill just use sth more mainstream so i can find more tutorials
i ggt
gtg
there are examples provided
cya later
why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd
hello, one question, theres anyway to limit @bridge.bridge_command() to a guild?
you use mongodb? I have this bug where like after I insert something into the database anything after that line doesn't get executed the command just stops, its so weird is it the same for u?
If I have same commands.Cog.listener() in two different cog files, will both of then run or only one of them will run?
I use mongo and works fine for me.
Both will run.
thanks
idkk what I'm doing wrong, I'm stuck with this problem for 3 days now
Mind sharing your command.
ok
@commands.command(name = 'createfaction')
async def create_faction_command(self, ctx, *, faction = None):
print('ok')
user = ctx.author.id
if faction == None:
em = discord.Embed(
title = "Help ๐ ๏ธ",
description = '**d.createfaction [faction name]**\nCreate your Faction',
colour = discord.Colour.yellow()
)
await ctx.send(embed = em)
else:
faction_name = faction.capitalize()
if self.collection.count_documents({ "leader": user }, limit = 1):
await ctx.send(f"{ctx.author} You already own a Faction!")
elif self.collection.count_documents({ "_id": faction_name }, limit = 1):
await ctx.send(f"This Faction already exists!")
else:
await self.collection.insert_one({"_id": faction_name, "leader": user})
await ctx.send (f'{faction_name} Created!')
the command works
await self.collection.insert_one({"_id": faction_name, "leader": user})
await ctx.send (f'{faction_name} Created!')
In this scenario the bot wont send a message but if I write
await ctx.send (f'{faction_name} Created!')
await self.collection.insert_one({"_id": faction_name, "leader": user})
It will send a message
Does it insert the document?
yes it does
But just wont execute the command after that
so uh I just tested something I removed the await before self.collection and now it works
huh
so much time wasted over 1 small thing
huh alright, my friend just uses async and he says that it works for him
I should note that if your DB queries are well optimised, you don't need Motor. PyMongo works perfectly.
okay ty
No worries
Hey, how i can create a count? Not 1, 2, 3, 4.. count only one number example: 23 User. i hope to understand this
for user in ctx.guild.members:
if user.status != discord.Status.offline:
print(user)
variables
yeah but how ?
make a list and use len()
or that
so?
for user in ctx.guild.members:
if user.status != discord.Status.offline:
print(len(user))
Yeah that's not how it works
I'm pretty sure for loops, lists and variables are basic python
and then i am a superhero? 
so i know how i create a list but a if is dont working in a variable (list)
What
How what?
your sentence is confusing
why?
i know im not the best in english
Use the translator then
Ok
So I know how to create a list, but you can't write an if query in a list as far as I know, or am I wrong?
because they both use the same namespace and having both installed breaks everything
oh ok
well I'm continuing my bot and gotta make a battle system
So before that i gotta make an inventory so can ya help me and give some pointers of how should i proceed
Its like. You first try doing something and ask here if you encounter any issues.
alrighty
any ideas why i get this error?
File "c:\Users\alexj\Desktop\EpicGiant Bot\main.py", line 3, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
do you have pycord installed?
pip show py-cord
yes
(venv) PS C:\Users\alexj\Desktop\EpicGiant Bot> pip show py-cord
Name: py-cord
Version: 1.7.3
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Pycord-Development/pycord
Author: Pycord Development
Author-email:
License: MIT
Location: c:\users\alexj\desktop\epicgiant bot\venv\lib\site-packages
Requires: aiohttp
Required-by:
theres your answer
oh yeah
upgrade to py-cord==2.0.0rc1
alr
How do i make pressing a button edit an embed which has been sent in a previous command? I get the error:
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
class join_ticket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(row=0, label="Join Request", emoji=':no_entry:', style=discord.ButtonStyle.grey, custom_id="delete_ticket", disabled=False)
async def button_callback2(ctx, message, interaction: discord.Interaction):
guild = bot.get_guild(901481491337465928)
req_embed = discord.Embed(title="Request!", description=f" is looking for a !\nOther Trader: {interaction.user.mention}\n\n**Trade:**\n\n> {interaction.user.mention} has joined the ticket!", color=0x40C96B)
req_embed.set_footer(text=f"Request")
req_embed.set_thumbnail(url=guild.icon)
await interaction.edit_original_message(embed=req_embed)```
why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd
How do I get a bot to return a message like this, where only the user can see it and they get the opportunity to dismiss it? I googled around, and looked in the documentation and couldnt find anything on it, although I might have just missed it.
await ctx.respond(content=โthis is a responseโ, ephemeral=True)```
thank you!!
what is ephemeral supposed to mean here?
Only the user who executed the command can see it.
If it is set to false, everyone with perms will be able to see right?
everyone who can view messages in that channel will be able to see it, yes
Also, how do I send Embeds?
await ctx.respond(embed=discord.Embed(title="test", description="test"))
just use its async branch: motor
its the same from inside but can be used with await
it works perf fine and my bot is verified
Is there a way to fetch a ton of random users from discord (tryna make a discriminator collector cuz dyno's stopped working)
AttributeError: module 'discord.commands' has no attribute 'group'
I call bs
should I not be using the alpha/master right now?
or is something screwed up in my venv
You could just generate random 18-digit numbers and use them as ID to fetch random users.
Question, what does AppInfo Module do? and how does it work?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'tuple' object is not callable
Using discord.TextChannel in slash command and fetching channel name with it throws this error. Anyone knows why?
why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd
How can i get the time on which my embed was created at
how can you keep buttons working after a restart of the bot?
i mean... dyno's only worked because the bot was in so many servers
and even then they said it was unreliable and removed it (though i wouldn't be surprised if there were other reasons)
the chances of you generating a random number and it being a real user is very low, so I wouldn't bother; you can only really work with users your bot can see
message.created_at
what version are you on
Here's the persistent example.
@upbeat hill refer to the above example
thank you
await bot.application_info() will return an discord.AppInfo object that has info about the application the bot belongs to that you created on the devportal
https://docs.pycord.dev/en/master/api.html#discord.AppInfo
development version i think
Version: 2.0.0b7
update to 2.0.0rc1
global lmao
id=doc.guild.id
lol=f"select sprefix from servers where sid={id}"
mycursor.execute(lol)
lmao=mycursor.fetchone()[0]```
so i want to call this function but it gives an error saying doc is missing and i can't provide a value for doc as it's the context nor can i remove it as it is required for variable id
so how do i call the function???
cus_prefix(ctx)
what does this do/mean?
Text Channels and Voice Channels
like #general is a Text Channel
i need to have that in order for Union[] to work?
what if i want 2?
discord.TextChannel and discord.VoiceChannel
Im not sure if it fixed
you dont need it in the []
yeah there's an error TypeError: issubclass() arg 1 must be a class.
?? wdym
Union[discord.TextChannel, discord.VoiceChannel]
wouldn't make a difference ig
doc is the parameter and you'll be passing ctx as the argument. So doc.guild.id will become ctx.guild.id
it just says ctx is not defined
Show your whole code if possible.
You need to call the cus_prefix(ctx) function inside the command.
like in each and every one???
That's up to you in which commands and where do you wanna use it.
But you can't pass ctx to it unless you call it inside the command.
it sets the prefix so won't i have to use it in every cmd
still doesn't work
error which occurs is
lmao is not defined
i added cus_prefix(doc) in evrery cmd and changed command_prefix to lmao
@warm tundra
Try like this:
def prefix(bot, ctx):
#Some code here to check prefix
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=prefix, intents=intents)```
in short it's of none type
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 793, in on_connect
await self.register_commands()
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 460, in register_commands
await self.http.bulk_upsert_command_permissions(
File "/home/container/.local/lib/python3.9/site-packages/discord/http.py", line 338, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed```
You need to return the prefix as string and it should not return None
so str()???
Update your lib version to 2.0.0rc1
Even if you return in str it should return some value and not None
k
what is command for that?
pip install py-cord==2.0.0rc1
still error sir
uh
cmd doesn't run and there's no error]
also
this is the value of str(cus_prefix)
<function cus_prefix at 0x0000026CA2CDD240>
show your function code which fetches and returns prefix
Oh Thanks, Nelo Can it be used to alter the application?
i don't think so
if im not mistaken most stuff on the devportal requires a bearer token and isn't exposed to being edited via the api
2> url=None disabled=False label='Delete' emoji=<PartialEmoji animated=False name=':no_entry:' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 367, in _scheduled_task
await interaction.response.defer()
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 471, in defer
await adapter.create_interaction_response(
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\webhook\async_.py", line 192, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
how do i get rid of this error when using a button to delete a channel
does it delete the channel or does it just throw the error.
And pls show us your code...
it deletes it but throws the error
Unable to get repr for <class 'discord.message.Message'>
Why is this error? I enabled the "message intent" on the developer site, but can't get the message content
actually I can't help you here. I'm not (yet) really familiar with buttons etc.
no worries, im thinking it is a timing issue
do you know how to make a incrementor for tickets?
what do you mean?
like ticket- 0001
ticket - 0002
etc
what about a simple file where the current incrementor gets stored and read from?
no idea how to use external file
well then learn python xD
https://www.w3schools.com/python/
Now that we have Permissions V2. How can I force a command to only work when they have X role?
Regardless what a server owner might set the permissions to?
@commands.has_role() decorator
basically what I'm asking
What are the new methods for is_owner and has_roles
^ which is a check, permissions v2 cant do this
I beg to differ? ๐
from the commands extension
discord.ext
message_group = discord.SlashCommandGroup(
"message",
"Interactions the bot can perform on its own messages.",
default_member_permissions=discord.Permissions(administrator=True),
)
Is this how one would set permissions v2 checks?
If not, how else and if, why doesn't it work on my server? No error, just still shows up to users that don't have the permission.
I think the default_member_permissions is a list, so try using default_member_permissions=[administrator=True]
I honestly don't know
it may be a tuple too
tias ig
One message removed from a suspended account.
https://docs.pycord.dev/en/master/api.html?highlight=textchannel#discord.TextChannel
e.g.
created = channel.created_at
One message removed from a suspended account.
Is it possible to list all available slash_commands with for X in X 
the docs are your friend. Use them.
try for command in bot.commands
this is for text commands
but nevermind, I found the solution
for application_command in client.application_commands:
print(application_command)```

idk
it does
is this possible to to?
@bot.event
async def on_error(error):
if isinstance(error, mysql.connector.Error):
print(f"MYSQL ERROR: {error}")
Does someone know how to use this? https://docs.pycord.dev/en/master/api.html?highlight=slashcommandgroup#discord.SlashCommandGroup.checks
I mean how to define the list of checks for the group.
||sorry I had to ๐ ||
disable_all_items() is not, well, disabling all items. Have I misunderstood?
class CancelButton(discord.ui.Button):
def __init__(self):
super().__init__(
label="Cancel",
style=discord.enums.ButtonStyle.red
)
async def callback(self, interaction: discord.Interaction):
self.view.disable_all_items()
await interaction.response.send_message("New trip entry cancelled.", ephemeral=True)
Is it possible to lock a private channel? Like people can see it but can't send messages
revoke their Send Message permissions?
Hi, does someone know to reload slash command choices for a user without reloading the whole bot?
without a cog btw
like I want custom choices for each user and add new choice without reloading the whole bot
is it possible?
Can I have the examples bots GitHub link pls
Is there any way I can make a message_command (ran from the context menu) silent? So it doesn't respond/ responds with an ephemeral message then deletes it
How do i remove the button after clicking it once with discord-components (cuz my pc sux and i cannot move to discord.py 2.0)
this isn't the discord-components support server.
you can defer the interaction or just not do anything but the user would see "The application did not respond."
alright
Ok thanks.
look for a cheap bot hoster, you'll find many if you just use google...
Or do you mean free hosting?
um
i use uptimerobot
its free
and to run it i use flask server
but if i turn my pc off for logic reasons the flask server file will not be running anymore
then 24/7 host in visual studio code is complicated
File "C:\Users\Me\Downloads\Python\Bot\commands.py", line 68, in send_announcement
webhook.edit(name=ctx.author.display_name, avatar=ctx.author.avatar)
File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\sync.py", line 850, in edit
payload["avatar"] = utils._bytes_to_base64_data(avatar) if avatar is not None else None
File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 523, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 509, in _get_mime_type_for_image
if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
AttributeError: 'Asset' object has no attribute 'startswith'
What am I doing wrong? Want to set the webhook's avatar to the author's avatar?
do I need to do Asset.read()?
Ahah! That's what I needed to do
Case closed
@dategroup.command()
@has_permissions(administrator=True)
@option("year", description="RP Year")
@option("month", description="RP Month (Default: Jan.)", default=1, required=False)
@option("day", description="RP Day (Default: 1st of the month)", default=1, required=False)
@option("sep", description="IRL days per in-RP year (Default: 2)", default=2, required=False)
async def set(self, ctx: ApplicationContext, year: int, month: int, day: int, sep: float) -> None:
"""Sets the RP date."""
rpdate = RPDate(year, month, day, sep)
io.save_rpdate(rpdate, ctx.guild_id)
await ctx.respond(f"Successfully set RP date to {rpdate}!")
@dategroup.command()
async def get(self, ctx: ApplicationContext) -> None:
"""Returns the current RP date."""
await ctx.respond(f"The RP date is {io.load_rpdate(ctx.guild_id)}.")
Is this well written? I can't help but think there are way too many decorators for this to be written properly
on_timeout event
thanks
How do I make something like this
where it says "Only you can see this"
use the ephemeral parameter
|coro|
Responds to this interaction by sending a message.
Parameters
-----------
content: Optional[:class:`str`]
The content of the message to send.
embeds: List[:class:`Embed`]
A list of embeds to send with the content. Maximum of 10. This cannot
be mixed with the ``embed`` parameter.
embed: :class:`Embed`
The rich embed for the content to send. This cannot be mixed with
``embeds`` parameter.
tts: :class:`bool`
Indicates if the message should be sent using text-to-speech.
view: :class:`discord.ui.View`
The view to send with the message.
ephemeral: :class:`bool`
Indicates if the message should only be visible to the user who started the interaction.
If a view is sent with an ephemeral message and it has no timeout set then the timeout
is set to 15 minutes.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
delete_after: :class:`float`
If provided, the number of seconds to wait in the background
before deleting the message we just sent.
file: :class:`File`
The file to upload.
files: :class:`List[File]`
A list of files to upload. Must be a maximum of 10.
Raises
-------
HTTPException
Sending the message failed.
TypeError
You specified both ``embed`` and ``embeds``.
ValueError
The length of ``embeds`` was invalid.
InteractionResponded
This interaction has already been responded to before.```
Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
-----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.```
oh cool
thanks
It worked
How can I get my bot to reply to webhooks?
Like the webhook says "?help"
and the bot replys with all commands
my buttons timeout after a certain amount of time and returns interaction failed, how do I make it so it never times out?
Here's the persistent example.
Is it possible to get a bot to use a slash command by sending a message? or is the only way to get a bot to use a command through sending a message to use prefix commands?
there's on_message but I don't recommend it
i want to get carlbot to periodically use a slash command
yeah you can't call a slash command from another bot
Quite annoying innit
is that an intentional limitation from Discord or has it just not been implemented?
Quick question: does discord.Option(discord.SlashCommandOptionType.user) always return an instance of discord.Member?
EDIT: Yup, they are
Slash commands are not processed like regular messages
it's intentional
Traceback (most recent call last):
File "c:\Users\DELL\Desktop\flash\bot.py", line 13, in <module>
bot.load_extension("cogs.ticket")
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 787, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 732, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.ticket' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'```
can anyone help?
is your bot a discord.Client?
If you are using a discord.Client it will not work with regular commands, only application (slash) commands
Change your bot object to a discord.ext.commands.Bot
my bot does not respond
try enabling the message_content and messages intent
in your dev portal and code
?tag missing_access
If you get a Missing Access (50001) error, you probably forgot to add the applications.commands scope.
To fix that, just replace YOUR_BOT_ID with your bot id and visit this link: https://discord.com/oauth2/authorize?client_id=YOUR_BOT_ID&scope=applications.commands
same
It didn't show up on the server
Bruh
He appeared
how do I get a channel ID from a database saved to my PC into a loop to send it to that specific channel?
because i have a loop and i want it to send messages to a channel set by users in a guild and the users in the guild can choose
so for each guild it's a different channel ID and a different interval of sending the message
No tag method found.
?tag method Not Allowed
No tag method found.
?tag Method Not Allowed
No tag Method found.
?tag 405
No tag 405 found.
Run a task that polls the entries from some database
Iterate over the entries
That would work to send a message to each of the channels in the database all at the same time
but what about having a different interval for each guild?
Then store the interval in your database..?
use thread.sleep
You can sleep the task, it'll block
await asyncio.sleep
where would i put that? in the @tasks.loop() function?
Yep.
If the intervals are regular, you can sort items with similar intervals together
then send out all the messages simultaneously too
I am a bit shaky on how the looping itself works so i'll send you my implementation of that which will probably be incorrect
@tasks.loop()
async def advance_date(self):
for guild_id in io.get_guilds():
rpdate = io.load_rpdate(guild_id)
if rpdate is not None and rpdate.channel is not None:
channel = await self.bot.fetch_channel(rpdate.channel)
await sleep(rpdate.advancement_freq)
channel.send(f"The RP date is {rpdate}.")
I don't really understand how this would send it at different intervals for each guild
^
sort them together
you could use a direct access array
for each interval, just store all the servers that need said interval in a linkedlist
For example
Guild A,B interval: 60s
Guild C,D,E interval: 65s
Guild F interval: 70s
ok wait hold on
Ok yeah sorry my method won't work
You can construct the Loop object manually, then add them to the task queue
no worries\
Construct the loop object and add them to the task queue
I do not know how to do that but i will research how to do it
discord/ext/tasks/__init__.py line 763
def loop(```
All the loop decorator does is spit out a Loop class
How can I do like create a dropdown and automatically select a option like in the video
Thx
How can i know that who clicked the button
idk why my test bot is unable to respond to any command
interaction.user
Prefixed commands?
yes
Do you have intents
bot = commands.Bot(commands_prefix='.',case_insensitive=True ,intents=discord.Intents.all())
interaction.user

One message removed from a suspended account.
hello, how can I create a loop that occures every day at midnight?
@tasks.loop(time=time(3, 0, tzinfo=timezone.utc)) # Task that runs every day at 3 AM UTC
async def time_task(self):
channel = self.get_channel(1234567) # Your Channel ID goes here
await channel.send("It's 3 AM!")
@my_background_task.before_loop
@time_task.before_loop
async def before_my_task(self):
await self.wait_until_ready() # Wait until the bot logs in
that is taken from the examples on github
ty
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
im getting this error but i have no clue why :3
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.
Hello! Small question, Is it possible to know if a user is marked as Likely Spammer? Or does discord not release that information to bots?
Thanks in advance!
just ignore it rn
oh its a bug?
Thank you very much!
One message removed from a suspended account.
bridge commands don't seem to work
if I use ctx.respond it says ```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
if I use ctx.reply it says the same but for applications commands
Your channel returned None.
py-cord version: py-cord==2.0.0rc1
Iirc it is ctx.send
One message removed from a suspended account.
Your channels returned None. What I just said.
ohh thanks, I was confused about it from the past hour...
Make sure you have intents.
One message removed from a suspended account.
it isn't responding to me directly in slash commands
I'd open an issue
how to access view in a button sub class
?
okay so i cant figure out how my slash commands are not updating/registring as new ones?
nvm i can use self.view to access the view
One message removed from a suspended account.
.timestamp()
channel.created_at.timestamp()
oh
useable on any datetime object
ok im slow at typing
it'sfine
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
just convert to int i guess
One message removed from a suspended account.
One message removed from a suspended account.
yeah
the comma is to represent the decimal time/milliseconds (this is a point in some languages, a comma in others)
One message removed from a suspended account.
Is it possible to deny users from interacting with buttons?
Check user's ID'S
you can override the view's interaction_check method to apply a check to all items in the view
if interaction.user.id != <your_id>:
return
And how'd I do that
are you subclassing?
I was already thinking of adding a user id check, but I've over 80 buttons so couldn't be the most efficient way
or are you just doing view = discord.ui.View(...)
view = View()
define a interaction check function
async def some_name(interaction):
... # Return True if valid
then just set view.interaction_check = some_name
this is always called before any of the callbacks, if it returns false the button's callback won't run at all
One message removed from a suspended account.
Thank you, I'm gonna try that right now
One message removed from a suspended account.
your max_time is in the future, so created < max_time is always true
i think you want current_timestamp - 3600; then < max_time is more and > max_time is less
(also you don't need timegm, you can just do date = datetime.datetime.utcnow().timestamp())
One message removed from a suspended account.
- too many brackets on that top line
2) you didn't need to swap theim bad<and>around in the ifs; think about what your code is comparing
oh wait my bad
your swap was correct
One message removed from a suspended account.
nono im pretty sure your change was correct
One message removed from a suspended account.
yes
One message removed from a suspended account.
all good
I cant get the timezone right. Do you know how to set it up correctly? In my case its Europe/Berlin
https://docs.pycord.dev/en/master/api.html#discord.SlashCommand.default_member_permissions provide Permission object
And how would I provide the Permission object?
Still normal cmds aren't working in bridges while using ctx.respond and if I use ctx.reply or ctx.send it wont work for application commands
Is there a way to call something else from a dictionary if key = value? Using the page dict(0) method is fine if I already know the dictionary. But what if Iโm looking in one with like 2000 results and I just want the โnameโ where โcolorโ = red
Update: Fixed
try:
send = ctx.respond
except:
send = ctx.reply
doesn't bridge add a new method that does that logic for you
Hey, how can I display what was clicked or added (in the select menu)?
Tried it with interaction.values, but it didn't work..
they keep receiving the regular Context object when they run the prefix version for some reason
i feel like this had a pr before but i might be wrong
yeah I remember this issue before
if you can directly reference your original select menu's variable, you can check select.values
otherwise, access interaction.data["values"]
Maybe this is a dump question but can you ping roles i interaction responses ?
I have a hard time doing so
uhhh yeah it should work fine
hmmmmmm
what were you trying
i doing a script that scan a lot of servers and if found a match send a match but if doesnt just give me a error can i make so when doesnt find send a error message
if allowed_mentions lets you, yes
By what is this defined ?
just have a variable that starts as False and turns True if you find a match...?
@slash_command(guild_ids=ConfigManager.get_debug_guild_when_debug())
async def ping_me(self, ctx, p: Option(discord.Role)):
await ctx.respond(p.mention)
It writes the mention just fine but i dont get the yellow background
does your bot have permissions to mention the role?
ok thanks
this is enabled so yea
and you definitely have the role you entered
webhook messages (which is what ctx.respond sends) are different
100% sure
Hmm thanks,
and how i can mention a role with this?
also can't @ here




