#Basic Pycord Help (Quick Questions Only)
1 messages · Page 83 of 1
Oh

what threw me off is that the original BasicModal class you pasted here did use add_item
Sorry, one more question (almost have Forms working now):
Is there a clean way to refresh a Page in Paginator? I have input coming from a Modal that updates the Page, but obviously those changes don't show rn without navigating away from that page
Would it just be edit_message and resend the Paginator?
If so, can I start it on a desired page?
Magnificent! I completely missed that
Thank you!
yay
how do you do prefix commands on pycord?
the same as whatever it was before
ion know
to be honest
don't know what it was before haah
what?
Learn how to use the commands extension for Pycord.
thanks
yes i have tried that and they don't work haha
is it something wrong with this line
bot = discord.Bot(command_prefix = "!", intents=discord.Intents.all())
yeah it's commands.Bot

- bot = discord.Bot(command_prefix = "!", intents=discord.Intents.all())
+ bot = commands.Bot(command_prefix = "!", intents=discord.Intents.all())
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
:D
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
and how do you do hybrid commands? i couldn't find that in the docs
prefix got an inbuild help command
Concept
@bot.bridge_command()
async def ping(ctx):
await ctx.send("pong")
in that case the slash command works but the ! command does not
if i use that then all of my slash commands dont work
ctx.respond
check intents
ctx.respond was the issue
^^
or not
all enabled
also at the website?
that's not how pycord works
!ping still isn't working 😭
do you have an on_message event?
@bot.command()
async def ping(ctx):
await ctx.respond("pong")
yes
thats why
change it to @bot.listen()
i've barely touched anything and now all of my slash commands have dissapeared?!?!?
😭
does anyone know something that would cause all slash commands to stop working
like not even showing up in the slash menu
quick question: can you subclass a discord.ui.View with a Modal?
Views and modals are different things.
seems like a discord issue
oh shoot okay
okay i see now, thank you
probably comment out everything, run the bot, uncomment everything then run the bot again
and then restart discord
uh
okay
yeah that didn't work whatever
ill just wait i guess
so damn wierd
yeah the slash commands dont show up but my prefix commands work
and i've waited an hour
and it's not just me
none of the server members can use it
try resetting the token and then do this again
ok
when I say run the bot, I mean wait until on_ready
yeah of course 
but i did it and it did not work
is this happening to anyone else?
could you print the commands out through bot.walk_application_commands?
how do i use that?
could you link the docs or ?tag it
.rtfm bot.walk_app
discord.ext.bridge.Bot.walk_application_commands
discord.Bot.walk_application_commands
discord.ext.bridge.AutoShardedBot.walk_application_commands
discord.AutoShardedBot.walk_application_commands
discord.ext.commands.Bot.walk_application_commands
discord.ext.commands.AutoShardedBot.walk_application_commands
version?
aiohttp 3.8.4
aiosignal 1.3.1
aiosqlite 0.19.0
async-timeout 4.0.2
attrs 23.1.0
autocorrect 2.6.1
boto3 1.26.140
botocore 1.29.140
cachetools 5.3.1
certifi 2023.5.7
charset-normalizer 3.1.0
discord 2.2.3
distlib 0.3.6
ffmpeg-python 0.2.0
filelock 3.12.0
frozenlist 1.3.3
future 0.18.3
google-api-core 2.11.0
google-api-python-client 2.88.0
google-auth 2.19.0
google-auth-httplib2 0.1.0
google-cloud-language 2.9.1
googleapis-common-protos 1.59.0
grpcio 1.54.2
grpcio-status 1.54.2
httplib2 0.22.0
humanize 4.6.0
idna 3.4
imageio-ffmpeg 0.4.8
iniconfig 2.0.0
jmespath 1.0.1
multidict 6.0.4
numpy 1.24.3
packaging 23.1
pip 23.1.2
platformdirs 3.5.1
pluggy 1.0.0
proto-plus 1.22.2
protobuf 4.23.2
py-cord 2.4.1
pyasn1 0.5.0
pyasn1-modules 0.3.0
PYCORD.PY 0.1.0
pycryptodome 3.18.0
pyparsing 3.0.9
pyspellchecker 0.7.2
pytest 7.3.1
python-dateutil 2.8.2
python-twitch-client 0.7.1
requests 2.31.0
rsa 4.9
s3transfer 0.6.1
secret 0.8
setuptools 67.8.0
six 1.16.0
tabulate 0.9.0
twitchAPI 3.11.0
typing_extensions 4.5.0
uritemplate 4.1.1
urllib3 1.26.16
virtualenv 20.23.0
wheel 0.40.0
wordninja 2.0.0
yarl 1.9.2
i should probably be using a venv but i haven't had any issues beause i use pycord for all my apps
done
didn't fix the no slash commands issue unfortunately
@bot.event
async def on_ready():
for command in bot.walk_application_commands():
print(command)
activity = discord.Activity(type=discord.ActivityType.watching, name="over TC")
await bot.change_presence(status=discord.Status.online, activity=activity)
print("Bot is fully functional and ready!")
print("----------------------------------------")
is this the correct usage of the walk application commands
yes
yeah means you have no application commands
cause even bots that are offline still show up in the slash command dashboard thing
right which is so strange
i most definetely do
.slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
tbh I don't think this applies to you since it was working before
right
plus all of those seem good
cause it makes no sense for a command like
@bot.command(server_id = server, name = "ping", description = "returns pong")
async def ping(ctx):
await ctx.send("pong!")
to not work
how are you defining your slash commands?
like that
and what is your bot instance, discord.Bot or commands.Bot or what
bot = commands.Bot(command_prefix = "!", intents=discord.Intents.all(), help_command=None)
that's not a slash command in commands.Bot
@bot.slash_command would be correct
anyone have a good way for users to input a date/time? rn im having them input a timestamp to make it easy for me. but theres gotta be a more user-friendly way.
rn it doesn't seem like it. although it seems like it is on the Discord API Developer's to-do list.
it has been there for at least 6 months tho, so I'm not sure about the feature's priority
you could always try to implement something. Parse the string yourself or something...
id still need to ask for their timezone eg. "UTC-3", so theyd have to look that up anyways
so im just sending them to a date/time -> timestamp converter website
alr, whatever works for you
trying to reload bridge command defined in cogs with bot.reload_extension() but raised error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'name'
I found in recent question history its a known issue?
fixed on master branch
MacOS?
Replit
Hmm dk
is there any way to edit an embed without touching the image inside it?
the images inside my embeds are uploaded, dont have a static url
so if i edit it and use message.embeds[0].url theyll eventually expire
i wanna edit the embed and keep the image in it as is
they do though
when you use attachment:// it's uploaded to the current channel
unless it's an ephemeral message, which is designed to expire anyway
yeah they're uploaded but I'm planning to edit the embed with more information in description once a certain user action happens
Now if i use the image URL as embed url and then delete the original image (since edited out) wouldn't it expire
uploaded image in embed
(Action 2 happens)
Image URL taken from embeds[0].image.url
Set new emb
Edited old embed with emb
removed old file with files = [] otherwise the image doubles one inside embed one outside
I have a workaround where I'll upload all images to a common channel and then use their url instead of directly uploading them to a main channel but I'd rather not to the extra work of migrating if there's a built in way to go around it
ping when reply ty
i didn't realise editing would double, pretty strange behavior, but it turns out you can actually set the image url to attachment://... again when editing to prevent that
Hey all, I have a persistent view with multiple select menus where MyView.is_persistent(MyView()) returns True, but when I restart the bot and try to reuse it, I'm getting "this interaction failed"
I'm using
async def select_callback1(self, select, interaction):
[...]
await interaction.response.defer() ```
between select menus. Is that the right approach?
Everything appears to work as intended until bot restarts. Any ideas?
are you using add_view on startup/ready?
Yep, hence the MyView.is_persistent(MyView()) returns True
well is_persistent only returns whether the custom_id was set by the user
Oh ok
but hm
can you show the full function that makes it persistent?
Yes but there's four select menus and a button so apologies in advance:
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None) # timeout of the view must be set to None
@discord.ui.select(custom_id="select-1",
placeholder="What kind of character is this?",
min_values=1,
options=[
discord.SelectOption(
label="Monastic",
description="Pick this if you plan to live in the founding monastery"
),
discord.SelectOption(
label="Representative",
description="Pick this if you plan to live in another clan"
)
]
)
async def select_callback1(self, select, interaction):
characterType = select.values[0]
self.s1check = True
await interaction.response.defer()
Then three more and a button:
@discord.ui.button(label="Submit", custom_id="button1", row=4, style=discord.ButtonStyle.primary)
async def first_button_callback(self, button, interaction):
if self.s1check and self.s2check:
await interaction.response.send_modal(bioModal(title="Modal via Button"))
else:
await interaction.response.send_message("Questions 1 and 2 are required to submit", ephemeral=True)```
Then:
```py
@bot.command()
async def select(ctx):
await ctx.send(
f"Make a Character Book! \n \n First, what kind of character is this? {MyView.is_persistent(MyView())}",
view=MyView())```
At the top of the file:
@bot.event
async def on_ready():
bot.add_view(MyView())
Does it matter that I'm using bot = commands.bot instead of discord.bot?
Edited to include the button if that's helpful
commands.Bot* discord.Bot* and for buttons no
But for commands yes
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
I don't understand. From that it seems commands.bot is not the problem
Happy to put this in a separate help post if that would be helpful
o so thats gonna upload the image as a file not as a url
for the embed
will that maintain the same imageurl after its uploaded as the previous one orwill that change
it doesn't reupload anything
the way attachment:// works is that if any files in the message have a matching filename, the file will hide itself and show in the embed instead
but when you edit the embed using that url, attachment:// no longer exists so it shows both
so the solution is to set it as attachment:// again
o so its gonna maintain the same file inside the embed
mhm
tyty
just checking, are you 100% sure it's not persisting or is it throwing some other error in your console?
Yeah no other errors and just "this interaction failed" when interacting with the previously posted select menus after stopping and restarting the bot
The docs say there is such a property? "If applicable" of course, but shouldn't it return None or False if it's not applicable?
how do I send a message to a channel without ctx (during on_ready())
Never mind I figured it out! I had two @bot.event async def on_ready(): in my code and that broke things. Sorry, my fault 😦
Get the channel, send the message?
.rtfm get_channel
discord.ext.commands.Bot.get_channel
discord.ext.bridge.AutoShardedBot.get_channel
discord.ext.commands.AutoShardedBot.get_channel
discord.AutoShardedBot.get_channel
discord.AutoShardedClient.get_channel
discord.ext.bridge.Bot.get_channel
discord.Guild.get_channel
discord.Guild.get_channel_or_thread
discord.Client.get_channel
discord.Bot.get_channel
Traceback (most recent call last):
File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
TypeError: on_ready() missing 1 required positional argument: 'ctx'```
bruh
I have ctx everywhere
Why?
@bot.event
async def on_ready(ctx):
# Embed Creation
mainchannel = bot.get_channel(main_channel)
await mainchannel.send(file=screenshot(ctx)) # Send the info message
why ctx
it doesn't like it for some reason
idk but when I get rid of it it gives me even more errors
() has to be empty
?
On ready doesnt take any parameters
How to make a simple slash command to show info about user?
Ok, I will try
But you know basic Python?
yeah I fixed it
it was a strange fix but I fixed it
"Strange fix" had to remove the argument
no lmao
not at all
I had to move my functions inside on_ready and then change some other things around
ok wtf is this
File "c:\Users\possi\Documents\Dev\discordlogger\mainrw.pyw", line 17, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
I did pip update discord and now it gives me this??
You must uninstall all discord related libraries and only install pycord
okay..
It is imported as discord
i have a problem sending a file to a user. Thats my code
if fileSize < 50000000:
file = discord.File(filename)
await channel.send(embed=embed)
await channel.send(file=file)
user = self.bot.get_user(322812067994140672)
await user.send(embed=embed)
if fileSize < 8000000:
await user.send(file=file)
The file was sended to the channel but not to the user, the embed is send to both, the file is not deleted. Is there anything i did wrong there?
No
You import discord
But install py-cord not discordn
The folder name is discord. The library on pip is py-cord
how to do interaction.response.send_message twice? looks like it can only be responded once
so I pip uninstall discord?
Interaction.followup.send
AttributeError: module 'discord' has no attribute 'Bot'
I just did pip uninstall discord
and made it called discord, same error
youre maybe in a cog
so it will be self.bot
No
@tired crag uninstall discord.py and py-cord and reinstall only py-cord
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
it will say this thing if you're ina a cog
Also discord-webhook
still same thing
Py-cord already have webhook
'commands' from 'discord.ext' (unknown location)
Isn't nextcord a Discord library too
It is
still the same errors
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
My man installed every possible discord api wrapper
I was tryna find the best one
You first fix your pip
wdym
You have like 3 discord libraries installed
I just uninstalled
use an venv
You have files replacing each other
AttributeError: module 'pycord' has no attribute 'Bot
show your code
which parts?
Why are you importing pycord
why are you doing import pycord 😭
because I just uninstalled discord??
please have a read
nvm shut up
pycord is discord
same error
like when you install pycord, you will have to use discord
show you code
what parts
You clearly don't know the difference between libraries on pip and on your actual computer. Not all libraries that you install from pip get imported with the same.name
pip install py-cord
import discord
thats what you do
the one with the error
I have a bunch of sensitive stuff on there
Not everyone at the same time pls guys ;3
I did
bot = discord.Bot()
exactly. even discord.py uses import discord lol
bot = commands.Bot(command_prefix="+",intents=intents, owner_id = owner_bot)
dark you'll handle this?
like this
but I don't use commands? I use slash commands
mhm
Only slash_command use discord.Bot
yeah so how do I use slash commands with it?
show your import
yk what do this
pip uninstall discord discord.py nextcord dissnake py-cord pycord
followed by
pip install py-cord
and keep the code unchanged
if you use slash command
i thing you can define bot = commands.Bot( intents=intents) like this
because i have some slash command and it work like this so
no need
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
yes but if it works
nice 👍
@untold spoke you dont need commands.Bot for only slash commands ;3
so you doesnt have installe a venv
i was thinking he already remove everything and this wasnt working but he doesnt so thats why i ask me to try it, sometime with the cache of a ide, you need to change some thing for it rework then
i know its strange but sometime i have to import discord as disc for it work and then reuse discord
using bridge command with typing var: Option(int) = 0
works for slash command
but error for prefix command discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "var".
is this because using wrapper on command?
just do var: int=0
okay thanks, also is there a option for command that ignore parameter such as **kwargs ?
when using **kwargs it gives discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
you can’t use kwargs for slash commands
Slash Command options have to be explicit.
try:
exec(code)
except Exception as e:
await ctx.respond(f'Error: {e}')
@bot.slash_command(name="execute", description="Code execute.")
async def execute(ctx: discord.ApplicationContext, *, code):
loop = asyncio.get_event_loop()
loop.run_until_complete(compile(ctx, code))
loop.close()```
Please help, await outside function error.
And i use nest_asyncio
is it possible to generate an invite link for your bot that's already directed at a specific guild and if so how?
I am trying to add the server Icon as a image to an embed, but I can't find how to do it, maybe that somebody wants to help
are you having trouble getting the image, getting the image to add it to the embed, or what?
booth
guild.icon works too
depending on where you want the image to be: https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Embed.set_thumbnail
or
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Embed.set_image
not unless you cast it to a string
when i do
embed.set_thumbnail(url=ctx.guild.icon)
i dont pass it into a string
but it still work so i dont understand what you mean
Guild.icon returns an Asset object.
the Asset object has a method that allows it to be converted to a string, but the same result can be converted to with Asset.url
so we dont need to pass ourself this to a string
its automatic
if i understand or im totally wrong
sometimes it is, sometimes it isn't
I got it working, Thanks!
for thumbnail and image it always works
have you an example of when this doesnt work ?
yeah, I agree, but it's better to know that you are dealing with an Asset object instead of an assumed string.
Please help
it's because someone was weirdly insistent on keeping forced string conversions in every embed attribute, and Asset.__str__ is just their url
how do i get the emojis in a guild
... guild.emojis
ctx.guild.emojis

what are you trying to do ?
@strong bobcat if you ask help then stop respond...
Execute python code
No
try to use the eval fonction
french ?
Looks like russ
I want to run Python code through a slash command, not at the compilation stage, but I get an error await outside the function
Russian
Ok
/execute await ctx.respond("1");
Error: Invalid syntax
show me youre code
it's the same code, only i changed exec to eval and didn't change anything else
it need to not be the same
so you will need to eval the texte
so you will have
@commands.command()
asyc def eval(self,ctx,*,text)
+eval(text)
for exemple
I have eval in another function in my code, due to await
you can just use an try execpt
it try with await
send without
Why not put exec inside of your execute function?
Await error
🤔
Await outside async function? That shouldn't be happening, because your function is async, can you send your full code? (Not just the function, but also the cog, etc)
-> #998272089343668364 message
Was this about me 💀
I did see your code, is the await outside async function error happening at the ctx.respond line?
I know the file= part is wrong, but how do i make it right :D
Yes
discord.File?
.rtfm discord.file
that doesnt help me
🤔 can you show pip list?
requirements?
Pass zipped_f to discord.File
:D
I cant
pip list > pip.txt <-- at the terminal
Hosting
Hmm
Yeah sorry it might mean you don't have pycord installed, but rather a different package under the same discord namespace because there's no way it would throw that error
Try putting the zipped_f.read() inside io.BytesIO(...)
No idea here sorry, :/
so
discord.File(io.BytesIO(zipped_F.read()))?
Btw Nullptr, how about you share the full error?
I use nest_asyncio
Isn't that for Jupyter Notebooks?
Also
thonk
Lmao
Is there any way to scrape stickers with pycord
There is neither a URL nor a read() to do that
there should be an url
idk if i'm in the wrong place but it seems right
lul
feel free to pr a read method
would be great
I just now wrote an emoji downloader which simply does emoji.read() and writes to a zip
Now i gotta figure out how to properly handle it only being a URL for stickers
yes, dw, i'm on it
just a bit inconvenient
was it?? i forgot what pr that was LOL
How can I make the bot go into "thinking mode" after executing a command and then respond?
?tag defer
No tag defer found.
.rtfm context.defer
In the Discord Server settings you can enable or disable certain slash command for certain users or roles. Is it possible to set a default for that in pycord?
Default member permissions? Checks? Or is it simply not possible?
.rtfm discord.default_
discord.Intents.DEFAULT_VALUE
discord.User.default_avatar
discord.TextChannel.default_auto_archive_duration
discord.TextChannel.default_sort_order
discord.TextChannel.default_thread_slowmode_delay
discord.Guild.default_notifications
discord.Guild.default_role
discord.commands.default_permissions
discord.MessageFlags.DEFAULT_VALUE
discord.WidgetMember.default_avatar
discord.Member.default_avatar
discord.TeamMember.default_avatar
discord.ClientUser.default_avatar
discord.ChannelFlags.DEFAULT_VALUE
discord.ForumChannel.default_auto_archive_duration
discord.ForumChannel.default_sort_order
discord.ForumChannel.default_thread_slowmode_delay
discord.MemberCacheFlags.DEFAULT_VALUE
discord.SystemChannelFlags.DEFAULT_VALUE
discord.Permissions.DEFAULT_VALUE
thx, I'll have a look at it
It's not possible to use roles or users specifically is it? I can't see anything like it.
And also is it already fixed that the default member permissions defined in a command group are also used by the sub groups? Because like a year ago this was not the case.
nothing changed
yeah those aren't possible under the current system
does the api not allow it or is it just not yet implemented?
they aren't possible under current api
that's too bad...
And the default_member_permissions actually don't translate to the command usage you can set in the server settings do they?
yup
Ok, well discord gotta change that xD
they won't
yes, and what a convinient coincidence: we have guides, docs and even examples!
literally look on github and the website lmfao
And also pls dont crosspost
don't minimod when i'm here zerv
Oh doch xd
And also, please don't crosspost
-to @young bone 1m no
⏱ Timed out zervyrel#0 for 1 minute
https://github.com/Pycord-Development/pycord/tree/master/examples there should be one
well breaking rules clearly does catch my attention, but i dont think people like the results

The 0 at the end looks so bad
Why did they not just removed it....
this, but instead of content you add an embed
and also, it's not adding a button to an embed. It's adding components to a message
the message just so happens to have embeds on it
well yeah #rules is "dont be a knob"
but #how-to-get-help with #help-rules is specific to avoid that we as helpers/devs get a headache from users
most big bots haven't updated yet
Only py-cord
probably so that they don't pull an ian
i have error with prefix commands using prefix
discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "miembro".
i get that error using Option() and the command, recomendations?
text-based commands don't use the Option class
ohhh
you only get to use converters like seen here: https://github.com/Pycord-Development/pycord/blob/master/examples/converters.py
¿What do you recommend, continue using the prefix commands or use the slash/application commands?
application commands because it's the standard
¿Do you recommend me still using bridge commands?
Hey y'all, been working on my first bot :) Was wondering if there was a way to render a button that is only visible to the author of a command?
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
e.g.
await ctx.respond("Imagine a message!", ephemeral = True)
await interaction.response.send_message("Imagine a message!", ephemeral = True)
Ah, I meant like the button ui element itself, not a message 😅
not possible
Unfortunate - thanks for the help!
probably the check to check if the author of the message is clicking the button if thats what youre going for
Is there a way to find users with their pomelo nickname?
How much RAM does an average sized bot need?
Really depends, but my bot uses ~300mb of RAM
how to do interaction.response.send_message twice or more for one interaction? for multiple condition
Wtf??
Shouldn't take more than 80-100mb
Use interaction.followup.send for the 2nd one
nosql db + a lot of image processing and caching
unknown webhook
Yikes
Hmm can you show what you are doing?
Lmao fr. 1gb is extremely large
free hosting
Fr 
How?
termux
With root?
no?
oof
Termux doesn't need root lmao
But my server literally fell off 2 times
async def callback(self, select, interaction: Interaction):
remove_role = [x for x in select.values if x in interaction.user.roles]
add_role = [x for x in select.values if x not in interaction.user.roles]
for i in select.values:
inter = interaction.user.roles
if i in inter:
for x in remove_role:
r = discord.utils.get(interaction.guild.roles, name=x)
await interaction.user.remove_roles(r)
await interaction.response.send_message(f"added {r} role")
if i not in inter:
for x in add_role:
r = discord.utils.get(interaction.guild.roles, name=x)
await interaction.user.add_roles(r)
await interaction.followup.send(f"removed {r} role")
Where can I see how much my bot needs specifically?
I don't think you can check how much your bot "needs"
You can always run and check how much your bot "uses"
hey, I have a python backend sending discord IDs to my frontend like below
@router.get('/bot_guilds')
async def get_bot_guilds():
return [
{
'id': guild.id,
'name': guild.name
} for guild in Guild.get_all()
]```
and receiving it in my frondend (ts) I push it into this structure
```ts
export type PGuild = {
id: bigint;
name: string;
icon: string;
owner: boolean;
permissions: bigint;
}
export class PartialGuild {
id: bigint;
name: string;
icon: string;
iconAssigned: boolean;
isOwner: boolean;
private readonly _permissions: bigint;
constructor(data: PGuild) {
this.id = BigInt(data.id);
this.name = data.name;
[this.icon, this.iconAssigned] = PartialGuild.getIcon(data.id, data.icon, data.name);
this.isOwner = data.owner;
this._permissions = BigInt(data.permissions);
}```
could it be that the json in between can't handle the bigints? because sending this: `287585628852584460` in my backend ends up as `287585628852584448n` in my frontend
try to pass id as str
for slash command autocomplete, is it possible to have different display value and actual parameter?
did not see any on the example
what type of view is this? i need to know the name
yes; in your callback, return a list of OptionChoice instead of strings https://docs.pycord.dev/en/master/api/application_commands.html#discord.OptionChoice
the recieved variable will be the value as a string; note that as always, you need to still validate that value since autocomplete isn't enforced.
found it thanks
Does someone know how to unlock a database ?
i always get this kind of error and the only way i found is reload the bot
self.cursor.execute("INSERT INTO embeds (guild_id, embed, title) VALUES (?, ?, ?)", (interaction.guild.id, str(embed_dict), str(original_embed.title)))
sqlite3.OperationalError: database is locked
but is it possible to just reload all database without reload the bot ?
How do y'all feel about hosting a bot on a raspberry pi?
I host my bots on a Raspberry Pi
Anything I should be aware of? Any issues?
Do you have a good Internet connection?
hey, how can i make a discord timestamp with :R out of this?
https://max1385.no-friends.xyz/UxFNSQe4.png
nvm, I have it
prob only specific to me but i tried setting up ssh and after a bit the wifi module literally just disappeared now no matter how many times i reinstall i don't have wifi
I'm currently getting a new router, should be better afterwards
Where do you keep your pi? Did you print some kinda case?
And did you install a fan or anything for cooling?
If you don’t have a good connexion like me, I host my bot on oracle cloud free tier.
You need to use a credit card to confirm your account (they take some money but give it back to check so no fake cards) and afterwards you have up to the equivalent of 24Go of RAM and 4 cores (and 200 or 250 Gb of storage i think)
import discord
from discord.ext import commands
from base.cog import BaseCog
from utils.emojis import Emojis
from views.selects import DropdownView
class VoiceSetup(BaseCog):
def __init__(self, bot: discord.AutoShardedBot) -> None:
self.bot: discord.AutoShardedBot = bot
@commands.slash_command(guld_only=True)
async def setup(self, ctx: discord.ApplicationContext) -> None:
embed = discord.Embed(
...
color=self.bot.user.color
)
embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar.url)
embed.set_footer(icon_url=ctx.author.avatar.url, text=f"{ctx.author} 測試")
view = DropdownView(self.bot)
await ctx.respond(embed=embed, view=view)
def setup(bot: discord.AutoShardedBot) -> None:
bot.add_cog(VoiceSetup(bot))
for some reason, the user.color always returns the color black.
sorry, I was trying to get the banner color
i have a problem sending a file to a user. Thats my code
if fileSize < 50000000:
file = discord.File(filename)
await channel.send(embed=embed)
await channel.send(file=file)
user = self.bot.get_user(322812067994140672)
await user.send(embed=embed)
if fileSize < 8000000:
await user.send(file=file)
The file was sended to the channel but not to the user, the embed is send to both, the file is not deleted. Is there anything i did wrong there?
can't get the banner color; User.color refers to their rendered color in the chat (i.e. the colour of their highest color role)
you can't send the same File object multiple times https://docs.pycord.dev/en/master/api/data_classes.html#discord.File
File objects are single use and are not meant to be reused in multiple
abc.Messageable.send()s.
(also fwiw, it's possible to send that uploaded file inside the embed rather than as a separate message)
it´s a video file. i want it under the embed. if i send it inside, the file is above the embed.
ahh fair enough
What´s the way to send it multiple times?
just create another discord.File
ok thanks
How to do button counter
Idk if im stupid but why does
message = await ctx.respond(...)
await message.edit(...)
not work?
"interaction attribute has no interaction edit"
Ah yea thx, forgot about edit_original_response
or ctx.edit()
hey, so im wondering if its possible to do multipstep autocomplete?
so i have the first command that uses autocomplete to select a variable in the config file for a server. would it be possible for the 2nd options input / autocomplete to change depending on the 1st selected?
such that if option 1 was "autoban" it would be true/false
but if it was "accountageflag" it would give you the ability to input day/month/year and then the amount?
ty 😄


i've got a cog for a bot like this
from discord.ext import commands
import discord
from cogs_list import cogs_list
class Utils(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
async def testcommand(ctx: discord.ApplicationContext):
await ctx.respond(cogs_list)
def setup(bot):
bot.add_cog(Utils(bot))
on line 3, "from cogs_list import cogs_list" when running the bot from the main file using
for cog in cogs_list:
bot.load_extension(f'cogs.{cog}')
i get the error:
discord.errors.ExtensionFailed: Extension 'cogs.botutils' raised an error: ModuleNotFoundError: No module named 'cogs_list'
but when adding
...
from cogs_list import cogs_list
print(cogs_list)
class Utils(commands.Cog):
...
it prints the cogs just fine, why does it do this? it works when printing the variable normally by running the cog on it's own, but when calling it from the main code, it doesnt work
Why do you import the cog?
inside the cogs_list is
cogs_list = [
"cogname"
]
it's so the main file can load the cogs and so the "testcommand" can list them for future use
(testcommand will be renamed and should have @discord.slash_command too)
hold on, i got it to work using
from . import cogs_list
...
await ctx.respond(cogs_list.cogs_list)
Just use the os.listdir module and load the cogs
oh yeah, duh
Or you could pass the folder name and set recursive to True in load_extension
That would load all cogs from within that folder (and any subfolders)
👀
alright, thank you 👍
hey i got problem about installing pycord
py-cord or pycord?
py-cord
And what is the problem?
i'm already installing py-cord but when i run code containing slash_command it doesn't work
?tag idw
do you actually import that?
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.
yup error : no mudule named slash_command
from discord import slash_command
.
Show the pip list pls
@patent knoll @young bone we don't need 3 people.
Yea i mean, i was already there
Same ;3
But I was the first one helping ;3
ah yes
my discord bugged again and stopped showing messages above that, the last message above the one i responded to is hours old
bye
should i uninstall discord py when i'm using py-cord?
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
thx sm
rHello,
Help, my two buttons don't line up. Do you have a solution? The spaces no longer work.
My perfectionist side is going to kill me
Is there a event i can use to know when the bot goes offline (ex, shutting it down from docker)?
i tried using on_disconnect but it doesn't appear to fire
discord isn't very kind with this, you have to guess or do more padding with blank chars
not really, we have on_diconnect for Discord Connection closing and some HTTPExceptions but closing it from docker might bypass that?
You may be better off overriding run, or making a command to handle the shutdown instead
fair ig
does anyone know what the boxes are and how i can add them in
Q: What is the activities return type in the tuple? (property of Member)
https://docs.pycord.dev/en/stable/api/models.html#discord.Member.activity
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 ...
Would it be good if I added that to the docs
how do I get an user's avatar?
user.avatar.url (using display_avatar.url instead will return guild-specific avatars and default avatars if they haven't set one)
For docker Linux containers (idk how this works w/ Windows containers), SIGTERM is sent to each process to shut everything down. By default, this simply stops execution of your program, but if you want your program to something else when it's told to shut down, you can catch SIGTERM by attaching a handler to the event loop your bot runs in https://docs.python.org/3/library/asyncio-eventloop.html#unix-signals m
Also see the signals stdlib (you can have bad results if you try use only this with an async program tho)
Hey, I don't want any code, but can someone give me a basic outline for the logic behind a slash-based custom help command?
.rtfm walk_app
discord.ext.commands.AutoShardedBot.walk_application_commands
discord.AutoShardedBot.walk_application_commands
discord.ext.commands.Bot.walk_application_commands
discord.ext.bridge.AutoShardedBot.walk_application_commands
discord.Bot.walk_application_commands
discord.ext.bridge.Bot.walk_application_commands
.rtfm slashcommand.description
Target not found, try again and make sure to check your spelling.
.rtfm applicationcommand.description
Target not found, try again and make sure to check your spelling.
Uh huh
Oh lmao I was iterating and enumerating through bot.commands
Lol that's for prefix cmds
I'm using bridge anyways so it doesn't matter anyways lmao
Also, how can I get a set of all the commands on my bot in the guild of ctx?
My syntax highlighting is broken lol
and my intellisense
YES I FINALLY GOT THE THING!
bruh files are terrible for mobile users
It gets around the message limit (to a point) ¯_(ツ)_/¯
paginators
how so?
It's just a pain to set up
ig trading your ux for that is too much
💀 I just realized how large my bot is
It looks so small when split across cogs but...
Dang
average projects
This was before I thought of files:
hi, my code was working before, however I factory reset my PC and reinstalled python and packages. I receive this error on my code: Module 'discord' has no attribute called 'Bot'. How can I remedy this?
Did you uninstall discord.py and install py-cord?
...let me go do this
welp no change this time
my terminal does not recognize discord.py at all now though
can you show your pip list?
what are the exact errors?
where can i find it?
Use "pip list" in the terminal
module 'discord' has no attribute called 'Bot
If you're using mac, it would be pip3
windows
uninstall discord, py-cord and reinstall py-cord
restart IDE/terminal/whatever you use to run your bot
yeah nothing
or more correctly, kill it and do it again
same thing?
yes
how are you running your bot?
through vsc
specifically how? Using a run button?
yes
the version of the python you have selected, could you check it's pip list
this wasnt it?
well, I don't enough information
oh okay, how can i find the more specific list?
the standard pip could be different than the python you're running it from
and this seems to be an installation fault
makes sense
do you see this or something similar on your vsc?
It should be on the bottom right corner
try using the global one
fuck ms store python
i wonder why the microsoft store vs is different?
No way its Marc
installs in a different spot
that makes a lot of sense. thanks
hey guys, I currently have this paginator that refuses to send. I switched to paginator.send() over paginator.respond() because the embeds were taking too long to build, and now it is giving me this error that I do not understand. Any help would be appreciated!
Please put your errors and code in a codeblock so its easier to read
.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.")
the line which is causing your error, isnt in the screenshot
also like the error says you have to pass ctx
@wheat stirrup
@slash_command(name = "rankings", description = "view the server points rankings", guild_ids=guildIDs)
async def rankings(self, ctx: ApplicationContext):
db = await asyncpg.connect(user = 'postgres', password = 'gaming123', database = 'postgres', host = 'localhost')
result = await db.fetch(f"SELECT * FROM goosmus WHERE guild_id = '{ctx.guild.id}' ORDER BY gspts DESC, palpts DESC")
embed = discord.Embed(title=f"Goosmus Points Rankings", description=f" in {ctx.guild}", color = 0x5198e4)
leader = await db.fetch(f"SELECT * FROM goosmus WHERE guild_id = '{ctx.guild.id}' ORDER BY gspts DESC, palpts DESC LIMIT 1")
leadermem = await ctx.guild.fetch_member(leader[0]['user_id'])
embed.set_thumbnail(url = leadermem.avatar.url)
embed.set_footer(text="Use the arrows below to navigate the ladder")
embed2 = embed.copy()
embed3 = embed.copy()
embed4 = embed.copy()
embed5 = embed.copy()
embed6 = embed.copy()
embed7 = embed.copy()
embed8 = embed.copy()
embed9 = embed.copy()
discord_pages = [
embed,
embed2,
embed3,
embed4,
embed5,
embed6,
embed7,
embed8,
embed9
]
emojilist = {1: ':first_place:', 2: ':second_place:', 3: ':third_place:', 4:
':four:', 5: ':five:', 6: ':six:', 7: ':seven:', 8: ':eight:', 9: ':nine:', 10: ':keycap_ten:'}
paginator = pages.Paginator(pages=discord_pages, show_disabled=False, show_indicator=True)
paginator.add_button(pages.PaginatorButton("next", label=">", style=discord.ButtonStyle.blurple))
paginator.add_button(pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.blurple))
page_idx = 0
for i, v in enumerate(result):
i += 1
num = emojilist[i] if i in emojilist else f'{i}'
usid = str(v['user_id'])
goospts = str(v['gspts'])
palpts = str(v['palpts'])
member = await ctx.guild.fetch_member(usid)
print(f"adding member {i}")
discord_pages[page_idx].add_field(name=f'{num}: {member.name}', value=f'Goosmus Points: `{goospts}` Pal Points: `{palpts}`', inline=False)
if i % 10 == 0 and i != 0:
page_idx += 1
# await paginator.respond(ctx.interaction, ephemeral=False)
await paginator.send(ctx)
for the error
Ignoring exception in command rankings:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 976, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/root/goosmus/serverxp.py", line 192, in rankings
await paginator.send(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/ext/pages/pagination.py", line 973, in send
raise TypeError(f"expected Context not {ctx.__class__!r}")
TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>
that good?
Try removing the type hint here:
ctx: ApplicationContext
How to make it so that one person can press the button once. But the button must remain in working condition.
Is it possible to track the clicks of participants without issuing a role.
it still throws the same error
Why did you post this in #general too lol
Because I got no answer here lmao
And this is also not pycord related
In a discord.Option, how can I accept more than one input type?
You can't
Accept as string, and convert to whatever you want. That's your only choice
Does anyone know how I can add slash commands when the bot is as a class, so that it has a description and leads to a function?
example code:
class some_bot_name(discord.Bot):
def init(self):
<add slash command with description "abc" that leads to self.example>
def example(self, ctx):
await ctx.send("succesful")
Your request is sketchy af. If you don't need lib help, leave the server.
im sorry but how tat sketchy, i legit needed help testsing my join/leave thiiiiiiiiiiiingies but it ok
this server is not to get testers
If anyone is available to chat about ext.pages and persistence, it would be much appreciated! I'm beginning to believe persistent paginators are a thing of myth and legend 😅
wdym
Paginators are a subclass of views. So in theory, adding them with bot.add_view on_ready and giving each component a custom_id without a timeout would render the paginator persistent (i.e., able to be interacted with after a bot restart). But this doesn't seem to work
Paginators and persistent views are complex thing lol.
I'm not sure if someone succeeded trying to make them persistent. You should try searching older posts
I have to no avail. As far as I can tell, no one with similar questions has been successful
Yikes, anyone ever see the error
WARNING:discord.gateway:Shard ID None heartbeat blocked for more than 60 seconds.
And then the process being outright killed? (oom)
Well it is possible. Not very easy unfortunately
Is there regex aliases for prefixed commands?
And the main reason is not due to the code of paginator, but rather because the pages themselves aren't always constant
If yk
Are your pages constant? Or are they dynamic (based on any inputs)
Each page is just a static image
At this point I'd be happy with figuring out how to do it with just generic example text on the pages.
You could create a basic paginator
Yeah I have, that's what I've been toying around with. The most basic example on: https://guide.pycord.dev/extensions/pages/paginator-basics
I'd like to see it being possible with something really simple before trying to make it work with my usecase
I meant, a basic paginator using normal views, doing it yourself instead of using ext.pages
Oh I see what you're saying, yeah maybe. Would like to try everything here first though
When creating a slashcommand group, it returns that the command group has no attribute "name"
Oh then it might be possible
What i will do is, make a function, that returns buttons with custom ids set
.rtfm paginatorbutton
discord.ext.pages.PaginatorButton
discord.ext.pages.PaginatorButton.callback
discord.ext.pages.PaginatorButton.custom_id
discord.ext.pages.PaginatorButton.disabled
discord.ext.pages.PaginatorButton.emoji
discord.ext.pages.PaginatorButton.from_component
discord.ext.pages.PaginatorButton.is_dispatchable
discord.ext.pages.PaginatorButton.is_persistent
discord.ext.pages.PaginatorButton.label
discord.ext.pages.PaginatorButton.refresh_component
discord.ext.pages.PaginatorButton.refresh_state
discord.ext.pages.PaginatorButton.row
discord.ext.pages.PaginatorButton.style
discord.ext.pages.PaginatorButton.to_component_dict
discord.ext.pages.PaginatorButton.type
discord.ext.pages.PaginatorButton.url
discord.ext.pages.PaginatorButton.view
discord.ext.pages.PaginatorButton.width
Create a list of 5 buttons in that, and return it
Pass that to use_custom_buttons in paginator
That kwarg might be named slightly different, not sure
Then make a paginator on ready, and pass it to bot.add_view
So smth like paginator = Paginator(..., use_custom_buttons=my_function())
Non async function btw
Do you mean in on_ready? like ```py
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#setup paginator here?
paginator = Paginator( ...)
If so, then how will I call it in a command since it will be out of scope? I still want users to be able to post the paginator even if its contents are static
yes
create a fresh pagainator for each cmd
the whole game is of custom ids
Ok I'm trying it, will report back!
Would it also work to use:
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
paginator = Paginator(pages=my_pages, use_default_buttons = False)
paginator.add_button(
PaginatorButton("prev", label="<", custom_id="paginator1", style=discord.ButtonStyle.green))
paginator.add_button(
PaginatorButton("page_indicator", custom_id="paginator2", style=discord.ButtonStyle.gray, disabled=True))
paginator.add_button(
PaginatorButton("next", label=">", custom_id="paginator3", style=discord.ButtonStyle.green))
paginator.timeout = None
bot.add_view(paginator)
When I use Paginator = Paginator(..., custom_buttons=my_function() I get Object is not Iterable error
you have to pass custom_id
keep in mind that self.current_page will not be ok prob
do you return it as array?
custom_buttons: Optional[List[:class:`PaginatorButton`]]
Sorry not sure I completely understand. I was hoping the paginator.add_button solution would get around making a custom button function.
def customButtons():
buttons = [PaginatorButton("prev", label="<", custom_id="paginator1", style=discord.ButtonStyle.green),
PaginatorButton("page_indicator", custom_id="paginator2", style=discord.ButtonStyle.gray, disabled=True),
PaginatorButton("next", label=">", custom_id="paginator3", style=discord.ButtonStyle.green)]
for x in buttons:
return x
paginator = Paginator(pages=my_pages, use_default_buttons = False, custom_buttons=customButtons()
TypeError: 'PaginatorButton' object is not iterable
Should customBottons() also be in its own class?
return buttons
not button (x)
Ah duh. Ok that solved the first error. The paginator now posts but it's not persistent. "This interaction failed" on bot restart.
Hmm
How do you add it in on_ready now?
Here's everything:
def customButtons():
buttons = [PaginatorButton("prev", label="<", custom_id="paginator1", style=discord.ButtonStyle.green),
PaginatorButton("page_indicator", custom_id="paginator2", style=discord.ButtonStyle.gray, disabled=True),
PaginatorButton("next", label=">", custom_id="paginator3", style=discord.ButtonStyle.green)]
for x in buttons:
return buttons
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
paginator = Paginator(pages=my_pages, use_default_buttons = False, custom_buttons=customButtons())
paginator.timeout = None
bot.add_view(paginator)
@bot.command()
async def paginatortest2(ctx):
paginator = Paginator(pages=my_pages, use_default_buttons=False, custom_buttons=customButtons())
await paginator.send(ctx)
Remove the for x in buttons line
It is simply return buttons
Hmm paginator.send might be doing some stuff
Ah turn off author check
Also pass timeout to the init ?
Where's author check?
And do you mean in the command like here?
@bot.command()
async def paginatortest2(ctx):
paginator = Paginator(pages=my_pages, use_default_buttons=False, custom_buttons=customButtons())
paginator.timeout = None
await paginator.send(ctx)
Cause I tried that already 😦
Hmm should be one of the parameters in the init
There are too many, i can't remember 😭
I was hoping this would work but no dice 😦
@bot.command()
async def paginatortest2(ctx):
paginator = Paginator(pages=my_pages, use_default_buttons=False, custom_buttons=customButtons(), author_check=False)
paginator.timeout = None
await paginator.send(ctx)
I tried author_check=False there and in the on_ready
Try calling paginator.update_buttons() in on_ready before adding
That has a strange effect. The interaction doesn't fail (so maybe progress??) but the pages don't change.
To be clear, the pages do change before restarting the bot
The internal page number would be outdated (because fresh Paginator thinks it is on the 1st page, but that might not be the actual page number)
You could do some "smart" workarounds
Such as? Not even sure what that means.
I do appreciate the help by the way. Really hope I can get it working
Ok this might be a bit weird, but it should be possible.
Make a subclass of PaginatorButton, and override the callback
In the callback, get the 3rd button in interaction.message.components (3rd button is index 2. This is the page indicator)
You will need to split the button label at / and get the first part. Convert it to an int. This is the current page number.
Set self.paginator.current_page to this
Then call super().callback with the interaction parameter
And use this subclass in your custom buttons function
Ok I'm trying
How to add a second button in a message?
Is this looking good?
class ButtonClass(PaginatorButton):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def callback(self, interaction: discord.Interaction):
test = interaction.message.components.__class_getitem__(2)
testsplit = test.split("/")
index = int(testsplit[0])
self.paginator.current_page = index
Must not be because now all interactions fail 😅
I can add 1, but how to make 2?
each view can have up to 25 buttons
And, how to make multiple buttons? Multiple classes?
create a view and write the buttons there
You gotta respond
I think the problem is also with __class_getitem__(2)
You can just do components[2] install of class getitem
Also you forgot to call super().calback
In a single class?
Where does super().callback go exactly? Sorry.
interaction.message.components[2] returns out of range by the way.
interaction.message.components[0] prints as:
<ActionRow children=[<Button style=<ButtonStyle.success: 3> custom_id='paginator1' url=None disabled=True label='<' emoji=None>, <Button style=<ButtonStyle.secondary: 2> custom_id='paginator2' url=None disabled=True label='1/3' emoji=None>, <Button style=<ButtonStyle.success: 3> custom_id='paginator3' url=None disabled=False label='>' emoji=None>]>
There's nothing in [1] or [2]
Yes?.. you can only send one view
Which can contain up to 25 components
At the end of your callback
Pass interaction to it
(It is an async function)
Oh right. Should be [0][2]
Still no good, unfortunately
class ButtonClass(PaginatorButton):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def callback(self, interaction: discord.Interaction):
test = interaction.message.components[0][2]
print(test)
testsplit = test.split("/")
index = int(testsplit[0])
self.paginator.current_page = index
await super().callback(interaction)```
Getting:
```py
test = interaction.message.components[0][2]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
TypeError: 'ActionRow' object is not subscriptable
Hmm try [0].children[2]
Btw that super callback looks perfect
Ok, progress:
interaction.message.components[0].children[2] prints as:
<Button style=<ButtonStyle.success: 3> custom_id='paginator3' url=None disabled=False label='>' emoji=None>```
so the split doesn't work: `AttributeError: 'Button' object has no attribute 'split'`
So is it the "3" that we want?
Oh actually I think we wanted <Button style=<ButtonStyle.secondary: 2> custom_id='paginator2' url=None disabled=True label='1/3' emoji=None>
The 1 from the 1/3.
So I got this now by partitioning the string, selecting the [label number], converting to int, and setting to self.paginator.current_page = index
But this doesn't play nice with the page numbers. When you hit the button to go to the next page it jumps two pages instead of one and is locked there.
= index - 1
so [0:N-1] for N pages
my pycord says that embeds cannot exceed 10 elements
but discord.py can?
A guide that shows the limits of embeds in Discord and how to avoid them.
what are elements
Ok so it all works now until the bot restarts. There is no 'interaction failed' but it doesn't advance pages and throws this error:
Ignoring exception in view <Paginator timeout=None children=3> for item <Button style=<ButtonStyle.success: 3> url=None disabled=True label='>' emoji=None row=0>:
Traceback (most recent call last):
File "python3.11/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "[myfile]", line 67, in callback
await super().callback(interaction)
File "/pythonProject/venv/lib/python3.11/site-packages/discord/ext/pages/pagination.py", line 120, in callback
await self.paginator.goto_page(
File "/pythonProject/venv/lib/python3.11/site-packages/discord/ext/pages/pagination.py", line 694, in goto_page
message_id=self.message.id,
^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'```
fields
Thanks btw
It depends on the length
I think something else is causing the issue cause I just tested with one embed field and it still says its exceeding 10
embed=discord.Embed(title="Earnest Ice Cream", description="Fraser Street Location", color=0xFF5733)
embed.add_field(name="Flavour", value="3", inline=True)
await ctx.respond(embeds=embed)
Hmm. Set paginator.message to interaction.message?
oh you're using embeds
yeah
this is what I get for having github copilot write it for me
How to make it so that one person can press the button once. But the button must remain in working condition.
Is it possible to track the clicks of participants without issuing a role.
This worked! A persistent paginator has been born! Many Many thanks to you 🙌
Store them in a variable? 
Woahh!! Awesome
Could you share the final stuff?
This would be helpful to future travellers on this path
Yes I'll post a guide, probably in my help thread
👍
Might be overlooking something very basic but.. I'm trying to send a message with my bot that pings a specific role. I'm using the syntax <@&[role id]> which gives me the correct role + color, but doesn't actually actually ping anyone with the role. The bot should have the correct permissions in the server it's in. Is there something I'm missing?
Oh I think I figured it out, seems like I can't ping in a ctx.respond ... is there any way to cleanly ping a role in response to a slash command?
@chrome ore are you using pycord?
yes
can you show the full error please
this is all what I am getting
I am trying my best to find a solution but i can't so i am coming here: I want the bot to play in a voice channel, i connect it and when it tries ```py
source = await discord.FFmpegPCMAudio("https://streams.ilovemusic.de/iloveradio1.mp3")
await channel.play(source)
i get an error
ffmpeg was not found
I can't find anything about that
What path? I only installed ffmpeg with pip
You did not post a python error
Oh this will be fun setting up on a remote server
I ll send you PM
please send it here unless it contains private information that you cant remove. This will help others be able to see how it was solved
cant can you please respond to my pm thanks a lot
So i installed it and added to path so cmd recognises ffmpeg as a command, but i still get the "ffmpeg not found" error...
How can I check if a server is a community server or not?
check if "COMMUNITY" is in guild.features
ok thank you!
or something like that
Squid maybe you know why my voice doesn't work? ^
yeah that's right https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.features
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 ...
try restarting the console and install py-cord again with pip install py-cord[voice]
I suppose if 'COMMUNITY' not in ctx.guild.features: would work, it just returns as a string in a list right?
is it possible to print the commands in all loaded cogs when the bot starts up?
something like
Logged in as [bot user]
Load cog: cog_name1
├─ command1
├─ command2
Load cog: cog_name2
├─ command1
├─ command2
Thanks a lot, it worked! 👍
Attributes description, qualified_name. Methods cls Cog.listener, def bot_check, def bot_check_once, async cog_after_invoke, async cog_before_invoke, def cog_check, async cog_command_error, def cog...
I'm trying to get my bot to send a message whenever someone says something in chat, but it doesn't seem to be doing anything, can anyone help me?
import discord
from core import Cog
class Responder(Cog):
def __init__(self, bot):
self.bot = bot
@Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot:
return
await message.channel.send('test message')
def setup(bot):
bot.add_cog(Responder(bot))```
Did you enable intents? (If you don't know what I'm talking about you probably don't)
@frail matrix
I think so, I have this in my bot.py file
class Milkbot(commands.Bot):
def __init__(self) -> None:
super().__init__(intents=discord.Intents.all())```
oh god thats embarrassing i just forgot to add it to the cogs in bot.py LMAO
thanks haha
that happens
i always forget 😐
What is the variable for server name and member count?
how can i add a upload attachment option to slash command
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...

Typehint discord.Attachment
I type guild.members and guild.name, and it did not work
.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.
Is it possible to see a WORKING example tasks loop
I'm studying now, and they write to me that the code given in the guide does not work
.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.
I have a code that sends a list. But I need the list to update itself every time after a reload. And I need the update to happen every 5 seconds
Simply put, I need to remove the blue button, and make the bot update this message itself, even after a reboot.
class TlB(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success,row=1)
async def button_callback(self, button: discord.ui.Button, interaction):
guild = interaction.guild_id
msg = interaction.message
user = interaction.user
cursor.execute(f"")
db.commit()
cursor.execute(f"")
item2 = cursor.fetchmany(4)
db.commit()
b = "" ....
class NS(commands.Cog):
def __init__(self, bot):
self.bot = bot
game = SlashCommandGroup("newstate", "Various greeting from cogs!")
out_game = game.create_subgroup("teamlist", "Teamlist commands")
@commands.has_permissions(administrator =True)
@commands.guild_only()
@out_game.command(name='send', description='Displays TeamList.',guild_ids=[944934277777326090,769823680695107594])
async def teamlist(self , ctx: discord.ApplicationContext,*,time: Option(str,max_length=17, description='Start time')):
cursor.execute(f"")
item2 = cursor.fetchmany(4)
db.commit()
await ctx.respond("Done.",ephemeral=True)
b = ""
i = 0
for el in item2:
i+=1
b += f"**{i}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"
cursor.execute(f"")
item = cursor.fetchmany(26)
db.commit()
a = ""
f=4
for el in item:
f+=1
if 4<f<17:
a += f"**{f}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"
if f>16:
a += f"Res.🔴**{f}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"
await ctx.send(f":scroll: __**TEAM LIST**__ :scroll:\n**🕐Time: `19:00` Moscow **\n \n{b}{a}\n \n
`•To confirm participation, click on :white_check_mark:\n•1-4 vip slots.`",view=TlB())
Regarding this code, where you need and how to insert it correctly tasks.loop
how can i make multiple thread to a slash command so every can run command at a time
i just put a while loop in 1 command and it's never end
and then run it 2 time
and got this error
you can fit the task loop in your cog and start it
the docs example demonstrates it best
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
ok thanks
what are you trying to do...?
While loop in a slash command 
you should really avoid while in commands unless you have a guarantee that it will end quickly, otherwise your entire bot stalls
um debuging python on slash command
and when i put while 1: pass to it
and its stuck at the first command
you can't even attempt to do that with slash commands because of restrictions with interactions
its a command
for WHAT
you're probably looking for asyncio.run, but either way while is always blocking; it's only worth using if you actually have something awaitable
debuging python
yes
Lmfao
having an eval or debug command is very normal, but while will always block your bot and you will have to restart
💀
You're expecting to be able to handle an infinite loop? It's codings basics you never do that
it's as simple as not using while in the first place
why???????
idk
maybe i can understand while k < 100 and increment k or something but that's just a for loop
if there's no condition to end the while loop then you're literally killing your bot
💀 :(
While loops must have a condition that breaks them.
There's no usage.for infinite loops other than wasting time and resources
can i use threading with my slash command?
Yes
@tasks.loop(minutes=1.0)
async def update_gaw_embed(self):
print('loop running')
await self.bot.execute("DELETE FROM giveaways WHERE startTime + duration < (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - INTERVAL '2 days';")
giveaways = await self.bot.fetch("SELECT * FROM giveaways;")
for row in giveaways:
channel_id = row['channelid']
custom_id = row['customid']
start_time = row['starttime']
duration = row['duration']
print(row)
print(channel_id)
print(custom_id)
print(start_time)
print(duration)
channel = self.bot.get_channel(channel_id)
message = channel.get_partial_message(custom_id)
duration_seconds = duration.total_seconds()
end_time = start_time + timedelta(seconds=int(duration_seconds))
print(end_time)
current_time = datetime.utcnow()
if current_time > end_time:
print('checked time')
await message.edit(content="The giveaway has ended!")``` how can i check the time so that it edits the message? currently the start time, duration, and end time are in order: 2023-06-16 11:05:50.951275
19524 days, 11:06:11
2076-11-28 22:12:01.951275 seems like my calculation of end time is incorrect how can i fix this what am i doing wrong
wait how can i use threading inside a command
this code does not work
Not familiar with threading at all. Can't give you a good answer.
when reloading an extension after adding a slash command it does not appear to me, do I will need to restart the bot if I add a new slash command instead of just reloading an extension?
yes
(this may change in the future)
anyone knows how i can get the end_time and check for if its been finished yet
you cant directly use await inside threads
you need to use asyncio.run_coroutine_threadsafe
you will need to pass bot.loop to this
um how
well, you would need to show me more than this to understand the structure
ok
can you show what dep is
@bot.slash_command(description="Debug a python file.")
@option("attachment", discord.Attachment, description="Add a python or text file here.", required=True)
async def debugfile(ctx: discord.ApplicationContext, att: discord.Attachment):
await ctx.defer()
embed = discord.Embed(title="Debug", description="Running...")
code = await att.read()
msg = await ctx.respond(embed=embed)
o = StringIO()
try:
with redirect_stdout(o):
exec(code.decode("utf-8"), globals())
embed.description = "\n" + o.getvalue() + "\n"
except Exception as e:
embed.description = "\n" + str(e) + "\n"
await msg.edit(embed=embed)
?tag paste
would be easier
oh ty
hmm
Where’s threading in that tho? 👀
oh i removed it
wait a sec

