#Basic Pycord Help
1 messages Β· Page 39 of 1
hope it's random enough;
I suck at design stuff in general, but had an idea regarding embeds that turned out to appear quite nice.
I did screenshot the background color of my bots avatar (could ofc also be the background color of his banner if that's more suitable), used that to get the colors hex value and finally passed this on as the chosen color for the left stripe.
Looked really need and orderly π
Ah yeah, used the same technique but than background layouts became a thing
Now its quite.... weird
Damn u discord for not lettin us edit the opacity of the color.
Its all webscript anyways
But, the side color is fittin the embed color anyways...
Why the heck it got removed by me
There it is, the real question! : D
can someone refresh me, how do persistent views work again?
its been like a year since ive used them
I know you need a None timeout and to do something with like add_view on startup
Here's the persistent example.
@shadow bear
grand, thank you :)
I have a strange problem. I don't get most of the autocomplete events from discord? I have everything set up properly in pycord and the api (guild commands) shows that autocomplete is enabled, but I don't get the auto complete interactions...
What is weird too, is that that's mainly the case for only one option, the other works most of the time.
Is this a discord bug or a pycord one? Did anybody have this issue too?
if i used autocomplete i'd try to help :(
Is ot possible to have interactions like buttons and selects to keep working even after a bot restart?
#1132206148309749830 message
You might wanna open a post for that. Can you share your code too?
How can i solve unknown interaction error
use defer most of the time
but it depend what cause that
#1242987715344072805
if you are running code that takes a lot of time (>3 seconds) you need to use await ctx.defer() to tell discord you need more time to respond
oh thx
can you help me with this
@commands.slash_command(name="cases", description="Get Cases of verification.")
@option("cases", choices=['Member ID', 'Case', 'All'], required=True)
@option("user_id", description="The ID of the member to get cases for", required=False, default=None)
@option("case_number", description="The number of the case to get info for", required=False, default=None)
async def cases(self, ctx: discord.ApplicationContext, cases: str, user_id: int = None, case_number: int = None):
ah
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.1: Required options must be placed before non-required options```
first of all, add type=int to the option decorators for the user ID and case numbers
not sure if it picks that up from the function header typehint
remove the = None its useless since you put requiered = false and it cause u an error
like this
@commands.slash_command(name="cases", description="Get Cases of verification.")
@option("cases", str, choices=['Member ID', 'Case', 'All'], required=True)
@option("user_id", int, description="The ID of the member to get cases for", required=False, default=None)
@option("case_number", int, description="The number of the case to get info for", required=False, default=None)
async def cases(self, ctx: discord.ApplicationContext, cases: str, user_id: int, case_number: int):
?
better yes
does user_id is a discord ID ?
yup
so you should use str and not int, those id are to be as int
and after in the code you do user_id = int(user_id)
it can be discord.Member ?
yes
yeah it's better than str
but you shouldn't do that because you might wanna get cases for people not in your server anymore
i think discord.Member stops working for people not inside the server
also default = None is useless, when requiered = false, its None by default
i'm already make code for this
yea but if you do discord.Member as the option type, you physically cannot put in user IDs of people not in the server
i'll remove it
ahh true
actually i was wrong about that, i just tested it
it even somehow (??) works with people not sharing anything with the bot
so must be handled properly on discord's side already then
so yes, you can use discord.Member
depends in the member is in the cache of the bot
no
yes
No.
i runned the code and it shows to me the same error
I just tested it Luma
i picked you, my bot shares NOTHING with you, and i still was able to get your user object
try it out
really strange
yea as i said, discord must just handle it on its end
show your code again
for the choices, yes
but i just used your ID
no, use my ID
yea its kinda neat
but i guess now i need to add more safeguards to make sure that my member options actually only take members of the current server lol
all code of the command?
the top part
@commands.slash_command(name="cases", description="Get Cases of verification.")
@option("cases", str, choices=['Member ID', 'Case', 'All'], required=True)
@option("user", discord.Member, description="The ID of the member to get cases for", required=False)
@option("case_number", int, description="The number of the case to get info for", required=False)
async def cases(self, ctx: discord.ApplicationContext, cases: str, user: discord.Member, case_number: int):
are you sure the error comes from that command tho?
i think it might actually be because one of your options has the same name as the command itself
can you change the name of the "cases" option
what is the error ?
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.1: Required options must be placed before non-required options
remove the str, for ur choices=
only in the @option
that doesnt matter, str is the default anyway
i think its just this
lets try
i have a lot of option with the same name
and no issue
so i think there is an error that remove the @option reading and then it raise that error
(i got similare issue with that)
@commands.slash_command(name="cases", description="Get Cases of verification.")
@option(name="cases", type=str, choices=['Member ID', 'Case', 'All'], required=True)
@option(name="user", type=discord.Member, description="The ID of the member to get cases for", required=False)
@option(name="case_number", type=int, description="The number of the case to get info for", required=False)
async def cases(self, ctx: discord.ApplicationContext, cases: str, user: discord.Member, case_number: int):
can you tried that ?
whats the difference
that doesnt make any difference lol
it can
no
Because the 2 positional arguments are name and type, in that order
i always do it without the kwarg
yes in case that str is needed and that the thing im not sure for choices
since i never used type= for choices, that why i asked him to be sure, if its good else we know that not the issue
and it take 5s to test
i tried
probably because you indented it too far
it doesn't shows any eror
make sure its on the same level as the other commands, and not more to the right
from discord
all is good
show again then
?tag past
No tag past found.
?tag paste
Please copy and paste your code here. This makes it easier for everyone helping you.
can you put ur whole cog in it, easier
i was not there did u fix it ? if not i will give a look
how do I install pycord
pip install py-cord
see I thought it was ```python
pip install pycord
No, that's a very different package
the name was taken
i think my pycord is done
ββββββββββββββββββββββββββββββββββββββββ 1.1/1.1 MB 8.5 MB/s eta 0:00:00
Downloading aiohttp-3.9.5-cp311-cp311-win_amd64.whl (370 kB)
ββββββββββββββββββββββββββββββββββββββββ 370.8/370.8 kB 11.3 MB/s eta 0:00:00
Downloading aiosignal-1.3.1-py3-none-any.whl (7.6 kB)
Using cached attrs-23.2.0-py3-none-any.whl (60 kB)
Downloading frozenlist-1.4.1-cp311-cp311-win_amd64.whl (50 kB)
ββββββββββββββββββββββββββββββββββββββββ 50.5/50.5 kB 2.5 MB/s eta 0:00:00
Downloading multidict-6.0.5-cp311-cp311-win_amd64.whl (28 kB)
Downloading yarl-1.9.4-cp311-cp311-win_amd64.whl (76 kB)
ββββββββββββββββββββββββββββββββββββββββ 76.7/76.7 kB 4.2 MB/s eta 0:00:00
Installing collected packages: multidict, frozenlist, attrs, yarl, aiosignal, aiohttp, py-cord
Successfully installed aiohttp-3.9.5 aiosignal-1.3.1 attrs-23.2.0 frozenlist-1.4.1 multidict-6.0.5 py-cord-2.5.0 yarl-1.9.4```
you would also see it at github how to install it..
or the website
which website
the pycord website
any of them
?
whys it say 1992
that's an oddly specific date lol
because the timestamp comes from that year
interesting
convert it to unix seconds (or miliseconds)
Is there a way to implement a custom converter?
To convert input from bridge commands
I have an option with a list of choices, but I'd like it to ignore uppercase
specifically for regular commands
wdym exactly
@bridge.bridge_command(name="test")
@bridge.option("category", str, required=True,
choices=['Collection', 'Balance', 'Inventory'])
async def test(self, ctx, category: str):
...
With slash commands this works fine, but when using a non slash command you need to type it exactly like "Collection".
I would like ti so that a lowercase version works
if you input "collection" I would like it to go through
add it to the bot
?
btw you dont need required=True
The following section outlines the API of Pycordβs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
from discord.ext.bridge import AutoShardedBot
bot = AutoShardedBot(
command_prefix=get_prefix,
case_insensitive=True,
intents=intents
)
When I run that command and try lowercase I get
discord.ext.commands.errors.BadArgument
how many guilds does your bot have?
evening, how is it possible to make slash command groups which are like /group subgroup command?
with slash groups and sub groups
;3
slash groups.supgroups?
what?
I mean this mb
you already got anything for it at that one screenshot
Any way to limit discord.ui.user_select to certain members?
no
I guess I'll iter through the guild members then and filter it
you could use a normal select menu but it got a limit of 25 and only strings
Well there goes my plan then
UI components are neglected af by discord
Nah i didn't fix it
import discord
import os
bot = discord.Bot()
token = os.environ.get('TOKEN_DISCORD')
@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: discord.ApplicationContext):
await ctx.respond("Hey!")
bot.run(token)
Basic code from the docs, but the slash commands are not showing up. What could be the reason?
FIXED
just re-invite the bot
but why did this happen?
you had to refresh your discord app
.noshowing
.tag noshowing
Tag not found.
.tag slashnotshowing
Tag not found.
Did you mean...
slashnoshow
slashcmdnoshow
slash no show
.tag shashnoshow
Tag not found.
Did you mean...
slashnoshow
slashcmdnoshow
slash no show
.tag slashnoshow
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
ctrl+r - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
@harsh bloom
No
It really isnt
I've been here for long enough and seen enough people to judge that as one of the issues that happens rather rarely
you're just biased because it's the issue you had and were probably annoyed with / spent a lot of time trying to fix
how to add icon to an embed's field? like this, add_field doesn't have emoji parameters
You can do it with the emoji id and name
The dyslexia
Itβs being on iPhone in the morning
What is on iPhone?
The fact that I was not able to type slash no show was because I was on iPhone
And kbm small
- autocorrect
- im finding excuse
lul
When I send an ephemeral response, I get a discord.WebhookMessage object back, right? I can use this object to update the ephemeral message. Does this webhook have a 15 min timeout like interactions have? Also, how would I save this in e.g. a database and reconstruct it again? What data would I need to save for that?
in ui components, how to add new buttons/select menu in specific row when editing the message from another button?
you can specify the row with row = number in the component decorator
i mean i know that, but its for creating a new button in that view, but i want to do something like a message contains 2 buttons, when clicking the second one, it edits the message and adds a selectmenu under the buttons and remove one button and so on, like making more modifications for the components
It depends on how you are adding the button to the message
ok i got an idea, i have to create another ui.View and edit the message to that ui.View right? lol
is this what you were looking for?
so remove_item exists aswell?
perfect, tysm
Is it possible to finish a method after await interaction.response.defer() without sending a followup message?
I have the problem that await interaction.response.defer() forces me to send a followup message and not defering leads to discord showing an error message since I dont want to send a response at all
why do you defer at all then?
you also need to send a response without deferring tho so what
I was doing a
try:
await interaction.reponse.send_message(content=None)
except:
pass
And in my memory it was working
why lol
To answer a response without sending message
but why the try
To show the animation while its doing things. But I just want the animation to stop if it finished without sending a response
Without try except it will raise an error canβt say empty message
will try that thanks
So use follow-up not reponse since itβs how u reponse to a message after defer
cant you also just edit the interaction message but change nothing?
But wouldn't a clear indication that whatever the bot is doing is done be better?
Thatβs smart, however in his case it would not help
Yes but their will not have the thinking thing that he needs
defer, then edit lol
How ?
Nope after defer you canβt use interaction.response
yea, i really hate interactions
why not just send an ephemeral message saying "Success" or something?
yea thats also waht i thought
if the loading circle just disappeared i'd think "ok did it work now or what"
just edit the actual message itself?
And for Tetris I wasnβt wanting each time a message or that will be unplayable
Haha that also worked with the followup, nice! Thanks! π
It would have raise a rate limit
Because there was already a loop
To edit the message for the piece moving down
With pleasure ;)
did bot send pics using url with file changed? i always post like this recently
here's the way i used for few years, but not work recently
@commands.command()
async def test(self, ctx: commands.Context):
file = discord.File(io.BytesIO(requests.get('https://imgur.com/...').content), 'test.png')
await ctx.send(file=file)
if you download the pic, does it work properly?
now not lol, i remember it was ok. it says {"data":{"error":"Imgur is temporarily over capacity. Please try again later."},"success":false,"status":403}
so it's not changed, got it, thanks!
imgur api has been pretty unreliable
discord also don't let people use it as pic storage; is there a better way if have to use url instead of local? google cloud?
Why don't you just send the imgur link directly
i feel ugly to show the url in the msg lol, it shows url if sends url with other text
doesn't it hide it for actual direct image urls that end in a file ending?
test
yea it does
i used the direct image link https://i.imgur.com/cnXPvXI.jpeg for that
damn
well, you can only listen for 403s on imgurs side then and retry or abort then i guess
i wonder what those 109 bytes even are tho lol
lol
how to change the bot avatar for a perticular server?
not possible
Use webhooks
when using the tasks loop decorator, how is the interval time calculated from the entered seconds minutes & hours. Are they all just summed together into a timedelta object?
What happens if seconds > 60 and minutes is also entered?
would be nice if devs could enter a timedelta object themselves
I mean, typically you don't change it often or have crazy intervals
Usually it's every X seconds or minutes or hours
And you typically only set it once
pretty sure it is yeah
just kidding, it does add them all together though
so you can have weird numbers
cheers for the reference link!
One quick question if someone uses a command X which has a cooldown enabled, can using different commands let's say Y can resets the cooldown for command X ?
Not that i know of, no
Ok, so we have to reset the cooldown in the same command?
think so yes
Ok thanks ππΌ
a very good way to hide? .
i don't think so
little confused, if i want to get the author of a message that someone replied to, do I have to do this?
class Foo(Cog):
...
@Cog.listener()
async def on_message(self, message: Message) -> None:
original_message_ref = message.reference
original_message_id = original_message_ref.message_id
original_message = self.bot.get_message(original_message_id)
original_author = original_message.author
because this seems really convoluted
if message.reference
author = self.bot.get_message(message.reference.message_id).author
that's cleaner certainly. I guess the answer is yes then
Hey guys, new to discord bot making as a whole but not new to python. For some reason I cant get Discord to display my new slash commands I added, or edited since the first run of hte bot on the server.
Basically, What i see for slash options are the ones that were present in the code when I first added the bot to the server.
restart discord
self.bot.get_message is returning None for the referenced message id. Is that because it isn't cached or something? Do i need to get the message object another way?
you can fetch it from the channel object (await channel.fetch_message(message_id))
i see, i'll try that, thanks
you should always try to get first though, fetching should be done as little as possible
is there any situation in which the get_message would succeed?
how do I add app commands
"app commands" aren't a thing, describe what you mean
slash commands
it should if it's cached, not sure why it isn't in your case
like the little menu you get to do a command
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
thx
app commands are literally short for application commands
Yes, but what would you say is an application command?
A slash command? A user command? A message command?
could be any of those
yes, if it was cached
application commands refer to the general category of them
Yea, but i still needed the exact command they want :)
And application commands might be the grouped name, but they're not a thing by themselves
if you get me
well i guess i'll keep the get_message and fall back on fetch_message if/when it fails
but saying that they donβt exist is just wrong

Isnβt there a get_or_fetch thing too?
no because they are under different objects
client.get and messageable.fetch
Ah makes sense
"sure, what kind?"
Thanks π
i keep on getting the "unknown integration" error when trying to run my bot
can you show the full error
ive got another issue
ive pasted my code and the @bot.commands() thing isnt showing up in the dropdown menu
one after the other
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True # Enable the members intent
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
print(f'Bot ID: {bot.user.id}')
@bot.command(name='ban_nuke', help='Ban all members who join in rapid succession.')
async def ban_nuke(ctx):
# Check if the author of the command has the necessary permissions
if not ctx.author.guild_permissions.ban_members:
await ctx.send("You don't have permission to use this command.")
return
# Get all members who have joined the server recently
recent_members = ctx.guild.members
# Define the threshold for rapid succession
threshold = 5 # Change this value according to your server's needs
# Check for rapid succession of member joins
if len(recent_members) > threshold:
for member in recent_members:
try:
await member.ban(reason="Rapid succession of member joins detected (anti-nuke).")
except discord.Forbidden:
print(f"Failed to ban member {member.name}#{member.discriminator} (ID: {member.id})")
await ctx.send(f"Banned {len(recent_members)} members for rapid succession of joins.")
else:
await ctx.send("No rapid succession of member joins detected.")
bot.run('NUHUH')
ok
also i just skimmed over the code but.. this would just literally count everyone in the server as "recent member"?
why is your prefix a slash?
im p sure your code would ban literally every member of the server as soon as more than 5 people are in it
So, unless I'm missing something, do not run that code lol
it doesnt even work
yea but if it was to work it would ban everyone in the server
no commands are even popping up
how come
wdym "popping up"
because its taking every guild member as recent member? lol
read your code
well yes, because they are prefix commands
so do i remove it
what?
the prefix
If you want actual / commands, you should use discord.Bot, and need to use @bot.slash_command
dude for real why
not if you define discord.Bot
why is that there
oh right
because someone here thinks its funny to be annoying and name themselves after a commonly used decorator
Also...
is that code from ChatGPT
its setting off my ai bells lol
why
because it very much feels like it is
is it?
genuine advice, dont take more code from your brother
he's either incapable of programming or wants to troll you
well either way, this
i didnt even read the code i will now
running code blindly is a mistake you make as often as it goes well, and only that often
(my brother)
yes
a function like that one requires a lot more code to actually handle the recently-joined-members tracking
i still think its chatgpt tho
all the comments (especially those), the use of old principles (discrims), the clearly completely wrong logic inside the code
i made a simple latency ping
import discord
from discord.ext import commands
bot = commands.Bot()
@bot.command(description="Sends the bot's latency.")
async def ping(ctx):
await ctx.respond(f"Pong! Latency is {bot.latency}")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}, Application ID: {bot.user.id}")
that's still a prefix command
how
because it is lol
a slash command is bot.slash_command when you use commands.Bot
again, if you only want slash commands, use discord.Bot
import discord
from discord.ext import commands
bot = discord.Bot()
@bot.slash_command(description="Sends the bot's latency.")
async def ping(ctx):
await ctx.respond(f"Pong! Latency is {bot.latency}")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}, Application ID: {bot.user.id}")
yea
.tias
tias
lol
ohhhhhhhhhhhhhhh
ty it works
now I have to learn how to use embed
use the docs, always
embed=discord.Embed(*insert
embed
stuff
here)
did discord changed something at the slash commands?
like what
I cannot get my command builder to add descriptions to it
import discord
from discord.colour import Colour
from discord.ext import commands
bot = discord.Bot()
@bot.slash_command(description="Sends the bot's latency.")
async def ping(ctx):
embed = discord.Embed(
title="Pong!",
description="NukeGuard's latency is {bot.latency}ms.",
colour=discord.Colour.blurple(),
)
embed.set_author(name="NukeGuard Team", icon_url="https://i.imgur.com/OVBw9iz.png")
embed.set_thumbnail(url="https://i.imgur.com/OVBw9iz.png")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}, Application ID: {bot.user.id}.")
you need to respond
how
same as you did earlier, but with the embed kwarg
embed kwarg?
await ctx.respond(embed=embed)
embed is a kwarg (keyword argument) because you're referring to it with a keyword
@wide hound that is not at beeing rude or anything but do you know basic Python?
should I be honest
we have an idea of the answer already but sure
not really no
your name already gives it away tbh
yep
i saw alot of discord bots and I was like "cool" so i kinda just
got into coding
sort of same
same here
I did some simple projects before
"why do i have traceback most recent call last error?!?!?!?!?!?!?!?!?"
like a yt to mp3 converter
in python?
lol
yes
thats just "error" in python
show the full traceback
the best ive done so far in python is a calculator but 1 divided by 0 crashes the program
at least it puts the error at the bottom where you can see it when the terminal scrolls
my discord bot is quite meh
ye
someone should make a graphing calculator on a discord bot
some are at the #creations channel
uh
is this normal
you forgot to make it an f-string
you just put f before the string
so it will run the code in the curly brackets
ok i will
Ive got the bot to send the response to the slash command, Is there an easy way (didnt see it in documentation) to replace that message with the response instead of a separate message?
edit the message
.edit_message(content="")
just out of curiosity, what is your bot for?
interaction.response.edit_message specifically
Im part of a group that archive and preserve old UK school software from a specific company (sounds dull, but they had full custom networks and everything, were very big back in the day) and this is a proof of concept for something we are working on to let others experience some of the software a little easier than before. A lot of the software is not really out there anywhere else.
Anyone know why my Bot cant post in Threads? I have a command with -(text)channel and -text as args. But if the channel is a thread it keeps saying "{channelname} not found"
Even if i mention the bot in there (the thread) and it's added it doesn't work to find it
show your code
async def say(self,ctx, out : discord.TextChannel, *, msg):
self.bot.get_channel(out)
await out.send(msg)
The hell is self.bot.get_channel supposed to do there? Besides it makes no sense at all.
You're already typehinting discord.TextChannel, the library is already converting the argument to a TextChannel object
Does await bot.sync_commands(force=True) have an issue with 25 or more commands? Not sure why I'm getting discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form BodyIn 1.options: Must be 25 or fewer in length. on command registration
Aha, for future ctrl + f-ers, if you copy-paste the code to register a slashcommandgroup and you leave the name the same as another slashcommandgroup, it will throw the above error
chill
why are you using that
slash or prefix command btw
does anyone know what is wrong with my code
@bot.slash_command(description="A secret vault for keeping items. Do not enter your discord password.")
async def secret_vault_password(ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
modal = Password(title="Enter your **VAULT** password/passkey")
await ctx.send_modal(modal)
wait
istg if its what i think it is
bruh
well?
nevermind
python
bot.slash_command(description="A secret vault for keeping items. Do not enter your discord password.")
async def password(ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
async def ctx(ctx):
await ctx.respond("Hello!")
modal = password(ctx, title="Enter your **VAULT** password/passkey")await ctx.send_modal(modal)
still not working, i get the same error as before
Learn how you can implement Modals in your Discord Bot with Pycord!
send_modal has to be the first response
You have too many options, max 25
Consider using autocomplete instead
hi, can someone tell me what im doing wrong?
@other.command(name="test1", description="big black balls.", options=[discord.Option(name="image", input_type=discord.Attachment, description="A file to attach to the message", required=True)])
async def test1(self, ctx: discord.ApplicationContext, image: discord.Attachment):
await ctx.respond("test")
Hi, simple question here- Is there a way I can store roles for future use? i.e., The owner configures the bot to give a certain role when achieving x level. I know this is possible, i've done it before, I just forget how
without options it works idk whats goin on
@other.command(name="test1", description="big black balls.")
@discord.option("image", discord.Attachment, description="A file to attach to the message")
async def test1(self, ctx: discord.ApplicationContext, image: discord.Attachment):
await ctx.respond("test")
This is how its usually done
that, or with a discord.Option typehint at the parameter itself but i hate that
can you have multiple option decorators?
yes
ok
.
sounds like the job for a database
i know it is a job for a database lol but what do i put in there?
and how to retrieve the roles again?
using a db library like mysql
thanks, it works now
you have to figure out what you need
but at the very least a role ID and server ID
I want to use these roles to assign them to users at a later date
how can I reconstruct a role from a role ID?
can you link docs? I couldn't find them
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
thanks a lot, any recommendations for an async db library? Does sqlite3 work?
mysql's library has an async part in it
but if you wanna use sqlite there's 100% an async version for that too
alright, I'll go look for that then
just 1 quick one aswell, how to add a role to a user?
nvm
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
docs are your friend
ik, sometimes it's hard if you don't know what you're looking for though
thanks a lot
np
but a role add would most likely be either in the guild, the role, or the member
so only 3 major places you need to check ;3
alright
Hi, can someone see what the sql error is? python await db.execute( f""" INSERT INTO roles_list( Guild_ID, Admin_ID, Tester_ID, LT5_ID, HT5_ID, LT4_ID, HT4_ID, LT3_ID, HT3_ID, LT2_ID, HT2_ID, LT1_ID, HT1_ID) VALUES ({ctx.guild_id},{ids[0]}, {ids[1]}, {ids[2]}, {ids[3]}, {ids[4]}, {ids[5]}, {ids[6]}, {ids[7]}, {ids[8]}, {ids[9]}, {ids[10]}, {ids[11]},) """ )
well, what does it tell you
how do i fix random unknown interaction errors?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
when using await ctx.respond
depend on ur code
it can be because it takes more than 3s so use defer will be efficient
Prefix command, I use slash a lot but for that purpose it seems to be better to use the prefix Version for formatting reasons
thanks, ill try
idk but im doing something like that, if that can help you
await db.execute(
"""
INSERT INTO roles_list(Guild_ID, Admin_ID, Tester_ID, LT5_ID, HT5_ID, LT4_ID, HT4_ID, LT3_ID, HT3_ID, LT2_ID, HT2_ID, LT1_ID, HT1_ID)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""",
(ctx.guild_id, ids[0], ids[1], ids[2], ids[3], ids[4], ids[5], ids[6], ids[7], ids[8], ids[9], ids[10], ids[11])
)
it can be easier to see which one is which one
for prefix or slash, you should not add self.bot.get_channel(out) for nothing
async def say(self,ctx, out : discord.TextChannel, *, msg):
await out.send(msg)
will be more logical since the out is already a discord channel object
i fixed it. There was a comma at the end that I didn't see π
@bot.slash_command()
async def secret_vault(ctx):
"""A secret vault for storing information."""
view = discord.ui.View()
view.add_item(discord.ui.Button(label="Enter your secret vault password"))
message_content = "This modal is for entering your secret vault password."
message = await ctx.send(message_content, view=view)
await view.wait()
how
check the guide
it doesn't specify in the docs when I last read it
it's all in the guide
can you send the link
pycord website > guide
and then UI components
ive read the docs and I still get the same erroras before
it doesnt specify that in the guide
Oh yes it does
so no
where?
in the UI components part lol
oh
i was looking at the sending modals through application thing
class MyView(discord.ui.View):
@discord.ui.button(label="Send Modal")
async def button_callback(self, button, interaction):
await interaction.response.send_modal(MyModal(title="Modal via Button"))
@bot.slash_command()
async def send_modal(ctx):
await ctx.respond(view=MyView())
now the slash command isnt showing up at all
how have 2 embeds in one message?
... that's hot how it works
the view class is entirely separate from your command
please check the guide
I think there's an embeds= kwarg in .respond so you can pass a list of embeds
I just corrected this, thanks. But it doesn't solve the issue
Is it just not possible like that to send to a thread because of the out : discord.TextChannel ?
hi, say I have an argument for a command which is text, how can I make it so that the argument MUST be one of a given fixed set? eg, it has to be a fruit out of the list [apple, banana, orange] ?
use the choices= kwarg
is that even possible?
I don't understand. Could you give me an example, or doc ref?
show the code of your command / the options
I haven't built it yet
something like this i want, if you understand:py @bot.slash_command( guild_ids=guild_ids, description="[Tier Tester Only command] - Award a tier to a player" ) async def giverank(ctx, args=[apple, banana, oranage]): pass
well I always recommend using the decorator
so
discord.option("optionname", str, choices=["choice1", "choice2"])
no lol
well yes but that's not how it works
ik so i use the decorator
yea
in that decorator, what does "str" mean?
the type of the option
you can only have choices for str and int and float options I think
or even just string
like the name, so if it was just async def giverank(ctx, rank), str would be rank?
"optionname" is the option name, and also the parameter it binds to
you can override it but there's really no need
thanks for the help
np
i have tried
await ctx.send(embed=[embed1, embed2])
embeds
oh thanks, it works xD
make one and see how it looks
alr
async def say(self,ctx, out: discord.abc.GuildChannel, *, msg):
channels_id = out.id
channel_or_thread = ctx.guild.get_channel_or_thread(channels_id)
print(type(channel_or_thread))
if channel_or_thread is None:
print("Channel oder Thread wurde nicht gefunden!")
return
print(channel_or_thread)
print(channels_id)
if isinstance(channel_or_thread, discord.Thread):
await channel_or_thread.send(msg)
print("Ist Thread!")
elif isinstance(channel_or_thread, discord.TextChannel):
await channel_or_thread.send(msg)
print("Ist Textkanal!")
else:
print("Kein gΓΌltiger Textkanal oder Thread!")
Still not able to post in text channels and threads. Even with all the prints if it comes to a actual thread it doesnt print anything lol.
Has anyone a function like that for their bot and could help me out?
how can I get the user who sent a command?
now how do I get the bot's icon because the docs says that bot.user is the bot's client when logging in and Client also has a .user with the same message?
what dtype is bot.user?
discord.User lol
damn it why does that have to say Client then? when they're 2 seperate thing
show?
property user
Represents the connected client. None if not logged in.
its confusing
meh, I mean it makes sense
ig
Hi guys. How send modal after ctx.respond?
not sure if that's possible
what's your plan with that command
You could try it with ctx.send_modal()
- Send welcome message
- Send message with select
- Send another message with select
- Send message with buttons
- Send message with select
- Send modal
I tried. I got exception InteractionResponded: This interaction has already been responded to before
That is, interaction with UI components generates a new interaction?
yes
it's in part to e.g prevent modal spam
so you can't spam the user with inescapable modals etc
Hi, how to remove a timeout using pycord ?
You first have to send the modal
i think its just member.edit(communication_disabled_until=None)
And then answer the interaction
communication_disabled_until=None*
sorry i forgot to check the documentation after checkung the guide
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
it's remove_timeout
ah, or that
lol that one just calls the exact method i sent
To send a modal you can only use an interaction response so if you first use ctx.response it will reponse so you will not be able to send modal
how do you pass a message id for an arg in a slash command? I try to convert all my prefix commands to slash but now i know why i skipped it the last time lol. It wont take message_id : int as arg. Well it takes it but i cant pass it
you need to use str as the type
IDs are too long for the length of integer discord allows
merci!
you might want to consider message_commands
I think I'm doing something stupid here: role = await ctx.guild.get_role(rank_id)
Why do I get TypeError: object Role can't be used in 'await' expression
its because you are using get_x
I don't get it
how might I approach resolving this?
remove the await
if you use fetch_x you have to use await but not at get_x
alright
so i have another silly error: channel = await bot.get_channel(announcement_channel_id)
that aint an error
TypeError: object TextChannel can't be used in 'await' expression
well, exact same thing there
Hello again, is it possible to make an image option for slash commands ?
remove it?
you are awaiting a non-async function
alright
discord.Attachment
it is not possible to specify the type of file you can receive
You can add an internal check to validate the file information and inform the user that the information they uploaded was invalid
thanks, i put this in the option type ?
you are already doing the right thing
itβs a matter of preference
sure, just wanted to show them another possibility
also, required is true by default, you dont have to explicitly pass it
how i have two "view" in one message? Example:
views=[Buttons(), Dropdown()]
or
view=[Buttons(), Dropdown()]
doesn't work
you can only have one view
a view can have multiple buttons/select menus
I have to do
await ctx.respond("Text", view=Button(), view=Dropdown())
For example?
a view can have multiple buttons/select menus
oh ok I just understand sorry
for example, MyView can have buttons + dropdown as same time?
yes
Okay π
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
oh I think I know why when I tried that it didn't work, I forgot to put row π
(I already tried to put everything in a view)
oh I'm stupid I put the buttons in another view that's why it didn't work π€¦ββοΈ
Sorry
there's any limitation of this options? like max 100 options
any work around?
oh! nice idea
(Not an official feature, just using buttons to make up pages; see ext.pages)
Hello all, how can I add slash commands to a slash command group?
Here's the slash cog groups example.
see the above example
(basically @group.command, where group is the group's variable)
Ok thx, I'll run it and see if it works
It can't find the module
are you coding on phone lol
you installed discord.py, not py-cord
Yeah xd
never seen someone who does
OHHH ok, I was working on it on discord.py originally
in the shell write this
pkg install py-cord ?
shell
pip uninstall discord.py
then:
shell
pip install py-cord
wait
nvm
what device are you coding from
an android phone
just the pip commands are enough
does pip work on android
I think so
do that
they're using python so it's probably fine Β―_(γ)_/Β―
how did you install discord.py in the first place?
on termux I think I used pkg or pip, not sure which
just try pip then
uh oh
It says discord.py was never installed π€
same error I encountered when trying to install arcade
Odd
what does pip list show
what about python -m pip list
Same thing
can you exit the shell mode so it shows the green file path again instead
like in cd storage?
cd to your bot's main path
oo ok
then after you're in the path run you pip stuff
did you change something to make it stop running?
yeah I added a lot of code
oh
but just now you're on python 3.11
oh how do I fix thay
well... the odd thing is that you used the same command
and it ended up with two different versions
what if you do python bot.py now
i mean after exiting python
ok we're getting somewhere
Yay :3
can you try typing python3.8
no space
ok good
now instead of pip, we use python3.8 -m pip
so try python3.8 -m pip install py-cord
oo ok
and if that works, python3.8 bot.py
exit() first
eyyyy
It ran all the way til line 104
i think ideally you uninstall 3.11 so 3.8 can be the default, but this should be fine for now
ok
sorry i guess my friend was helping me with the discord.py code idk how to change this
setchannel should be a command
it should be @misc.command()
that's from dpy, unneeded
nice
None of the commands show up
do you perhaps have an on_connect?
then,
- at what point are you running
bot.run - what's in your
on_ready
maybe it would be easier if they provided their whole code?
probably
Sure hold on
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.
oh wait i see
oo
oops, discord.SlashCommandGroup is when you're using cogs
cogs?
for regular bots, it should be client.create_group
Yeah it works now
Btw do you have a guide on how to restrict a bot only to talk in certain channels?
do you mean restrict commands?
Yep
there's two main ways
- channel permission
Use Application Commands - guild settings > integrations > you can set channels and roles here for the entire bot, or specific commands
that assumes you can edit permissions and such; if you mean on the bot's side, you can write a custom check
ooh which one would you recommend? I'm looking for something like
User: /restrict_to (channel1, channel2)
hm, what's your end goal? you want specific users to be restricted to specific channels?
Hmm, I want an option for anyone with the manage bots permission role in a server to be able to restrict the bot to their own #botspam for example
i guess there's two sides to this; the matter of hiding commands is completely on discord's end, you can't toggle it from the bot, so it comes down to an internal check
so i'd recommend using a db or whatever to save a config that checks if the bot is locked to a channel
then write a check as i linked above
you can either apply that check to individual commands, or enable a global bot_check
Yes I want a global bot check
then see https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.Bot.check for an example
what's the issue
I don't understand it at all
so here's the example py @bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commandsit uses bot, but in your instance it'd be client
this code will run on every command; if it returns True, then it's allowed to run
so in your example, let's say you have some sort of config file that contains a json of userid: channelid json { "242367619431268353": 1132206148309749830, }from what you described, you want something like
- if the user ID is not in this file, they can use the command
- if the user ID is in this file, if the channel id matches they can use the command
- if neither of the above are true, they can't use the command
(i'm just guessing, perhaps you want to test it works at all with a more basic condition)
well that's a matter of deciding how you want to save your data
ideally using some database library
okay
when it comes to the actual slash command, just make the option types discord.Member and discord.TextChannel
ctx is just ctx
you don't need to typehint it
(but if you want to, it's discord.ApplicationContext)
oh how do I check if the user has the manage bots permission? π
i assume you mean manage_server? or perhaps manage_webhooks
ok I'll try with manage_server
you mean guild?
oh forgot it was renamed
Ooo
all the guild-wide perms are on ctx.author.guild_permissions
or if you're using a command check, https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.has_guild_permissions
Like this or?
and if for some reason author doesn't exist, ctx.interaction.permissions as well
If this is supposed to be the check function for Bot.check, no, not really
The following section outlines the API of Pycordβs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
It's not, it's supposed to be the command that uses Bot.check
You create a bot check. It just gets applied to all commands.
You don't apply it to a command / the command callback doesn't call it.
Either way, it's wrong.
It's not the bot check to see if the bot is restricted, it's the command to restrict the bot. Hope that makes sense π
Yes, I know what you mean.
Let's. Let's go step by step.
- You have the restrict_to command. Which only users with the manage server permissions should be able to use.
Yep
- You have the other X commands which should be restricted in usage by the channels set in the mentioned command.
All of them except for a dif command called /unrestrict
So restrict_to and unrestrict shouldn't be affected by that setting.
Yep
Haven't stored it yet but maybe a list called restricted_channels
That will reset on every bot restart.
Simplest way is a json file.
Do you know how to store and fetch stuff from a json file?
Not at all
Great, you will google how to do that.
Okay
Okay it's telling me to use JSON.parse but I don't know how to specify where to parse it
Is the bot going to be global?
wdym
Like anyone can add your bot and specify their own channels
Yes
So you need to store config on a guild basis.
Yep
Well, I'd tell you to learn actual real databases cause json files aren't meant for bots, so...
.nojson
JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Donβt use json!
- It's a file-based data storage, which makes it vulnerable to race conditions
- You'll need to implement your own synchronization primitives to avoid corrupting data
- If you're not careful, you could accidentally wipe your entire JSON file.
Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.
- Async libraries exist on pypi for each of these
sqlite --aiosqlite(or Danny's wrapper: asqlite)
postgresql --asyncpg
mongodb --motor - Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
- You can impose uniqueness constraints to ensure against duplication
- The Python libraries enforce synchronization for you
- The query language is intuitive, you can get running with simple queries in just a few hours!
Most of the basics but barely OOP
Depends on the DB you wanna use, I personally use MongoDB, others use SQL
You need to dominate at least the basics of OOP, it'll be very helpful. The whole library is OOP.
Oo ty :3
@errant trout What do you recommend as DB for them
json 
If you want a "serious" suggestion uhhh aiosqlite is pretty good at this scale
guys, a question, if I add a new Slash Command and reload the extension is it automatically added in discord?
and what can I do in the meantime? Should I sync manually?
Just restart the bot
Only have to do that for adding/removing commands or updating their metadata (name, options etc), if you're just changing code then reload is fine
Ok, ty!
how to create threads ?
I made a bot in pycord which was working perfect but now it have stopped responding to my commands
how can I fix it up???
@errant trout
#help-rules

screenshot, error and code
Is it possible to make review buttons and modal windows that have them active for 48 hours?
class ReviewButtons(discord.ui.View):
@discord.ui.button(label="Review", style=discord.ButtonStyle.green, custom_id="review_button")
async def review(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = ReviewModal()
await interaction.response.send_modal(modal)
it just needs to be a persistent view
.rtfm persistent
discord.Client.persistent_views
discord.AutoShardedClient.persistent_views
discord.ext.pages.Paginator.is_persistent
discord.ui.Item.is_persistent
discord.AutoShardedBot.persistent_views
discord.ext.bridge.Bot.persistent_views
discord.ui.Button.is_persistent
discord.ext.commands.Bot.persistent_views
discord.Bot.persistent_views
discord.ext.pages.PaginatorButton.is_persistent
discord.ext.pages.PaginatorMenu.is_persistent
discord.ui.View.is_persistent
discord.ext.bridge.AutoShardedBot.persistent_views
discord.ui.Select.is_persistent
discord.ext.commands.AutoShardedBot.persistent_views
Its works, thanks
Ignoring exception in on_connect
Traceback (most recent call last):
File "/app/venv/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 1178, in on_connect
await self.sync_commands()
File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 754, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 588, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 588, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/venv/lib/python3.11/site-packages/discord/commands/core.py", line 875, in to_dict
"options": [o.to_dict() for o in self.options],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/venv/lib/python3.11/site-packages/discord/commands/core.py", line 875, in <listcomp>
"options": [o.to_dict() for o in self.options],
^^^^^^^^^^^
File "/app/venv/lib/python3.11/site-packages/discord/commands/options.py", line 337, in to_dict
"type": self.input_type.value,
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'value'
How can I debug this? the error gives me no information and I have over 100 commands to check through if I need to go through it manually
whatever you changed last is the issue
so funny story
I have had this error in my logs for like
a month
and just
haven't noticed
lmfao
I can't figure out how input_type would be None, doesn't Option() force it to be string if its not an InputType?
maybe you put bogus there
I've got an amazing idea
I'll just try parsing them all manually before registering
to_dict() is raising the error
so if I just iterate through all commands after loading them and calling it manually, I'll find out which command is whack
I don't appear to be able to do this
log.debug("Walking the following application commands: %r", list(bot.walk_application_commands()))
for command in bot.walk_application_commands():
log.debug("Checking %r", command)
try:
assert command.input_type is not None, "Input type was None!"
d = command.to_dict()
except Exception as e:
log.error("Failed to convert %r to dict", command, exc_info=e)
bot.remove_application_command(command)
else:
log.debug("Loaded command %r.", command)
bot.run(...)
Walking the following application commands: []
do you use cogs?
yes, they're loaded before this
this snippet is line 279-291 of my runtime file (newlines omitted)
the cogs are loaded just after the bot's instance definition just after line 130
I could try overriding on_connect's event and doing the validation in that function I guess
if you gonna do that you also have to sync the commands
I just called super()
which, still isn't working
class Client(commands.Bot):
def __init_(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.web: typing.Optional[asyncio.Task] = None
self.uptime_thread = None
async def on_connect(self):
log.debug("Walking the following application commands: %r", list(self.walk_application_commands()))
for command in self.walk_application_commands():
log.debug("Checking %r", command)
try:
assert command.input_type is not None, "Input type was None!"
_ = command.to_dict()
except Exception as e:
log.error("Failed to convert %r to dict", command, exc_info=e)
self.remove_application_command(command)
else:
log.debug("Loaded command %r.", command)
log.info("Connected to Discord.")
await super().on_connect()
am I missing something?
def walk_application_commands(self) -> Generator[ApplicationCommand, None, None]:
"""An iterator that recursively walks through all application commands and subcommands.
Yields
------
:class:`.ApplicationCommand`
An application command from the internal list of application commands.
"""
for command in self.application_commands:
if isinstance(command, SlashCommandGroup):
yield from command.walk_commands()
yield command
This is the source for walk_application_commands
so I cna only assume self.application_commands is empty for... some reason
which it really shouldn't be given I define one or two application commands in the runtime file, just after loading cogs
I am so confused right now
then id suggest showing your cogs and those 2 commands too
Hang on, I might try checking pending_application_commands
maybe application_commands only gets populated post-sync
that was it
jimmy-public | WARNING 2024-05-27 16:40:10 WARNING jimmy: No application commands. using pending.
jimmy-public | ERROR 2024-05-27 16:40:10 ERROR jimmy: Failed to convert <discord.commands.SlashCommand name=election> to dict
jimmy-public | Traceback (most recent call last):
jimmy-public | File "/app/main.py", line 125, in on_connect
jimmy-public | assert command.input_type is not None, "Input type was None!"
jimmy-public | ^^^^^^^^^^^^^^^^^^
jimmy-public | AttributeError: 'SlashCommand' object has no attribute 'input_type'
bingo
nevermind
idk why i tried to get the input type of the entire command lmao
Original issue was some command's option input type is somehow None, which is causing syncing to fail as it can't convert to dict
issue I just fixed was I couldn't walk the application commands to figure out which command it was
since this is run prior to the on_connect, im almost sure self.walk_application_commands() will be None, you might considere _pending_application_commands since there are still not register
so basically you have a command that cant be sync
are you are trying to know which one it is ?
Yep
I've got 10 cogs, and thousands of lines to comb through
so I wanted to just figure it out from the error
rather than going through manually
this traceback
and nothing after ?
jimmy-private | ERROR 2024-05-27 16:45:25 ERROR jimmy: Failed to validate <discord.commands.SlashCommand name=about>
jimmy-private | Traceback (most recent call last):
jimmy-private | File "/app/main.py", line 128, in on_connect
jimmy-private | raise TypeError("Input type is None")
jimmy-private | TypeError: Input type is None
There we go, found the violating command
nope, it just connected and continued as normal
Except my changes to commands weren't being updated, since it couldn't sync
hence why I just didn't notice for so long lol
@bot.slash_command(name="about")
async def about_me(self, ctx: discord.ApplicationContext):
...
return await ctx.respond(embed=embed)
Hold on, what option?
OH WAIT
i have a basic thing to help you, normally it just remove the command that is laggy so you can just check you help if you have one to see what command is missing
uh if we're counting since the first error, like a month
if we're counting time spent actively debugging, about an hour? half an hour?
only an hour is fine, hopefully it will not take longer next time
its fine, it was only 10 commits, which is less than usual 
why did you commit any of that
i like ur comment
