#Basic Pycord Help (Quick Questions Only)
1 messages · Page 72 of 1
Thanks ❤️ I ended up using a regular expression for validation 🙂
Follow up question: Is there an event or a way to print to console once all cogs are loaded?
For example, this is what I currently have ("Characters" is a cog):
04/20/2023 14:59:09: [Startup] Bot attempting to login to Discord...
04/20/2023 14:59:12: [Startup] TestBot9000#1577 is ready and online!
04/20/2023 14:59:12: [Characters] Successfully loaded!
But I'd rather it be like this:
04/20/2023 14:59:09: [Startup] Bot attempting to login to Discord...
04/20/2023 14:59:12: [Characters] Successfully loaded!
04/20/2023 14:59:12: [Startup] TestBot9000#1577 is ready and online!
"Ready and online" comes from bot event on_ready
just load cogs before connecting?
this is considered standard anyway since slash commands have to be loaded before on_ready fires
I thought I was...
# Create the bot object
bot = discord.Bot(intents=intents, activity=activity)
# Add cogs to bot
bot.add_cog(CogCharacters.CogCharacters(bot, db))
@bot.event
async def on_ready():
print("Online!")
bot.run(TOKEN)```
But the Characters cog is printing its on_ready after the main bot file's on_ready? Is that normal?
Is add_cog async?
nope
you could add in a await self.bot.wait_until_ready() in your other cog events
also if your cog is another file, it's recommended you load it as an extension rather than using add_cog directly https://guide.pycord.dev/popular-topics/cogs/
Wouldn't that wait to load the cog until after the bot is ready?
no, i mean inside your other on_ready events where you're printing stuff
That would be in the other cog files
I have a bot on_ready and then a cog on_ready for each cog. I just found it odd that the cog on_ready's were loading after the bot's on_ready
well the on_ready isn't for when the cog loads
it's just when discord cache is ready
the default bot.event is fired first, then the additional listeners are fired after
Ohhhh, I did't know that... Sorry. Maybe a better place to indicate that the cog was loaded would be in __init__?
yeah probably
Btw, what exactly is the Discord Cache (I'm still learning everything, sry)
Or, what does it being ready indicate?
well by default, if you have the members intent the bot will go through all your guilds and save all the members locally
so you can receive member related events and quickly interact with them
there's also the message cache and a few other small ones
oh cool, so it fires when it's queried the Discord API successfully and has cached all that data locally
mhm
is there a cache per cog? or is it global to the bot? Doesn't make sense to have a duplicate cache per cog
bot
kk, tyvm ❤️
e.g. you can access bot.guilds
gotcha
and for every guild you have guild.members
And just to learn, is there any particular reason to load it as an extension over how I'm doing it?
as an extension it's easier to update code on the fly without having to restart
wait whaaa... If I load it as an extension I can develop the code, save, and it will live update functionality without rebooting?
there's some caveats like not being able to update slash metadata (name etc.) but yeah
you load it with load_extension and you can reload / update with reload_extension; the best integration for this is to make these commands
hmm, that's super good to know, tyvm!
all good
oh, it requires a function call to reload? I'll look into that
mhm
Sorry for the ping @cyan quail, but is it possible to send extra data as arguments in bot.load_extension()? I need to send a database object that's defined in the main bot file to all the cogs, but I don't think I can with load_extension, which is why I think I'm using bot.add_cog 😅
don't bother sending it
you can access it directly through self.bot no?
Uhh... maybe? How would I make an instance variable within the bot object/class/whatever to store the DB object?
have you made a proper cog structure?
e.g. from the guide https://guide.pycord.dev/popular-topics/cogs/ ```py
import discord
from discord.ext import commands
class Greetings(commands.Cog): # create a class for our cog that inherits from commands.Cog
# this class is used to create a cog, which is a module that can be added to the bot
def __init__(self, bot): # this is a special method that is called when the cog is loaded
self.bot = bot
# commands etc.
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot
in your init we have self.bot = bot which is expected in all cogs
so here you can add any other variables you might need
Oh, yes, I have all this, but I currently have it like this:
class CogCharacters(discord.Cog, guild_ids=[GUILD_ID]):
def __init__(self, bot, db):
self.bot = bot
self.db = db```
But you said to not pass it as an argument and instead call it via `self.bot.db`? Which means it would be an instance variable of `bot`, no?
Yes. So, how do I make an instance variable for the bot object? Is there an __init__ for Bot as well?
did you already subclass bot
ah it doesn't look like you did, but it doesn't matter
you can just do bot.db = ...
isn't that bad practice and you should subclass bot instead?
Yeh, I don't think so... I just have a bot.py file and it does this effectively:
# Create the bot object
bot = discord.Bot(intents=intents, activity=activity)
# Start the bot
bot.run(TOKEN)```
though if you plan on doing it more extensively, adding several variables or overwriting several methods then yeah subclassing would make it easier in the long run
How do I subclass bot?
I think it's definitely not the best way, but again, that doesn't mean that's bad.
the same as how you'd subclass cogs, just make a class that inherits discord.Bot
though unlike cogs you need to include a super init
i'd recommend reading through https://guide.pycord.dev/popular-topics/subclassing-bots
Subclassing is a popular way of creating Discord Bots. Explore how you can create a Discord bot by subclassing.
subclass, also known as inheritance or extending.
Oh, perfect, thank you. This is what I needed to get the cogs (baddum-tish) rolling in my head 🙂
funny enough, none of the examples actually have an __init__
yeah...
I mean if you understand OOP you should know why+how you should subclass, right?
I know OOP concepts, but I don't know Python OOP syntax very well 😬
Just need to sit down and learn it...
usually I see people trying to speedrun making a super complex discord bot before they know the basics of computer science and/or python.
I believe it... I almost have my degree in CS and am super familiar with Java and C++, but Python syntax is still new to me. Trying to keep all my Python growing pains out of this channel though and only ask questions regarding the API. Thx for all the info peeps
Btw there is a way for it. Make a GET or HEAD http request to the url and check the content type
Here's the slash autocomplete example.
How fix this problem?
Some days I rly wanna slap you..
inform yourself before you speak or don't speak at all.
k
Can can pass names of Users if you want. And set value to the id
Oh damn that's a really old msg 💀
yes xd
That's what I did hah
Can you use utils.get_or_fetch() the same way as utils.get()?
look at the examples?
I'm a little bit stuck, I don't have much clarity. Can someone help me or provide a code to connect to a channel and play an audio file?
from discord.ext import commands
from discord_slash import cog_ext, SlashCommandOptionType
import asyncio
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.voice = None # Initialize the voice client variable
# Define a command to join a voice channel and play audio
@commands.command()
async def play(self, ctx, *, file_path: str):
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(ctx.author.voice.channel)
voice_channel = ctx.author.voice.channel
self.voice = await voice_channel.connect()
# Load the audio file using discord.py's FFmpegOpusAudio class
audio_source = discord.FFmpegOpusAudio(file_path)
# Play the audio file
self.voice.play(audio_source)
async def on_ready(self):
print(f"Logged in as {self.user}")
bot = MyBot(command_prefix="!")
bot.run("your_bot_token")```
chatgpt4 made this
Also someone help me, i have problem using slashes in class
@discord.ext.commands.is_owner()
@option('collection', description='Choose database', choices=['Games', 'Site exceptions', 'exceptions'])
async def add_to(self, ctx, collection: str, string: str):
listing = self.retreive_list(collection)
print(listing)```
What loses me a little bit is the FFmpegOpusAudio. Do you know if I have to have the audio in some format?
problem is that it asks for ctx as an input parameter in slash
how do i hide it?
About the choices?
it should be able to load, try it
yes, it asks for ctx parameter which should be automatic
What if you remove it?
then it puts ctx into self variable
I am going to check my commands
why do you have self 🙃
i have it in class
hey, i want to change every appropriate user. but my code doesn't work, please help me out somehow
@bot.event
async def on_member_join(ctx):
if "swearword" in ctx.username:
await ctx.edit("Moderierter Name")
else:
pass
await ctx.author.edit(nick=new_name)
I use autocomplete parameter
For example:
async def get_type_times(ctx: discord.AutocompleteContext):
return [
time for time in TIMES if time.capitalize().startswith(ctx.value.capitalize())
]
@option("type_time", description="Duration type", autocomplete=get_type_times)
async def vote(self, ctx, type_time: str):
...
but why doesn't that work, again i want to moderate every username made in the "or ..." thing
@bot.event
async def on_member_join(ctx):
if "swear" or "swear2" or "discord.invite" or ".gg" in ctx.username:
await ctx.author.edit(nick="Moderiert")
else:
pass
i see, u have wrong syntax: u need to make this if ".gg" in ctx.username and "swear" in ctx.username and .......for every one of your strings
ohh ok
it still puts ctx into self
it still doesn't work
@bot.event
async def on_member_join(ctx):
if "swear" in ctx.username and if ".gg" in ctx.username:
await ctx.author.edit(nick="Moderiert")
else:
pass
bru, I have no idea sorry men
do u have any errors
i think ctx.username doesn't exist
yeh it does
man whats in your console
if u don't have any console output that means u haven't turned on your bot
autocomplete=discord.utils.basic_autocomplete(<LIST>)
Try this
it is turned on
but u have console, right?
@bot.event
async def on_member_join(ctx):
if "swear" in ctx.author.name or ".gg" in ctx.author.name:
await ctx.author.edit(nick="Moderiert")
else:
pass
what
container@server~ if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/${BOT_PY_FILE}
Requirement already satisfied: py-cord in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 1)) (2.4.1)
Requirement already satisfied: aiohttp<3.9.0,>=3.6.0 in ./.local/lib/python3.10/site-packages (from py-cord->-r requirements.txt (line 1)) (3.8.4)
Requirement already satisfied: typing-extensions<5,>=4 in ./.local/lib/python3.10/site-packages (from py-cord->-r requirements.txt (line 1)) (4.5.0)
Requirement already satisfied: aiosignal>=1.1.2 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (1.3.1)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (3.1.0)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (1.8.2)
Requirement already satisfied: frozenlist>=1.1.1 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (1.3.3)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (4.0.2)
Requirement already satisfied: attrs>=17.3.0 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (22.2.0)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (6.0.4)
Requirement already satisfied: idna>=2.0 in ./.local/lib/python3.10/site-packages (from yarl<2.0,>=1.0->aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (3.4)
[notice] A new release of pip available: 22.2.2 -> 23.1
[notice] To update, run: pip install --upgrade pip
no
or vs code?
what's that
so u edit your code on hosting service??
yes
thats not correct way of doing it
you can't check your code, if it has any errors
use pycharm or vs to edit your code locally, then upload it onto host
both of these programs help you by showing ctx parameters such as author, send, respond....
and mainly it shows console output where are errors shown
we wont write and give you code
we just help you with errors in your code
and other stuff like ode structure etc
or how to do x, y, z
you need to do the coding part
||we are unpaid volunteers
||
Hi, anyone wanna guide me on how I'd go about making a verification system that uses Discord Authorization. Basically, they authorize their discord account on my website, and I give them the verified role, how would I do this?
when you don't understand how help channels work
nvm
i just figured it out myself
cause u guys don't know how to explain
Learn about handling OAuth2 on your website and using ipc to connect with your bot
Or unless you want to ping some api the bot listens to (no idea how to do that but it's an option)
ohhhhhhhhhhhhhhh ty
i really forgot wtf oauth2 was
and why it existed, i remember its basically the discord dashboard login
just the callback code is changed
Girl I saw the whole convo and you expect people to give you code when you don't even use a proper code editor. Get your things right
i am a boy
💀
Yes, it is the Discord login thingie
You just do different stuff lol
Np
It's used as a plural world. Not specific. Just like "bro". Don't get your masculinity offended darling.
this guy doesn't even know basic python syntax lol
not quite, it's used to do either a get_ method or fetch_ method if the item isn't cached
https://docs.pycord.dev/en/master/api/utils.html#discord.utils.get_or_fetch
Interms of usage what’s the difference
all utils.get does is return an item from any list
depending on some criteria
utils.get_or_fetch will parse your args to either return an item or fetch it. Let's take this docs example:py channel = await utils.get_or_fetch(guild, 'channel', channel_id, default=None)
this will do the following:
- try
guild.get_channel(channel_id) - if that returns none, it'll try
await guild.fetch_channel(channel_id) - If that also doesn't work, it will error. However by passing
defaultit won't error and instead just returnNone
Ahhh I seee. Was trying to use get_or_fetch to search for a category by name utils.get(interaction.guild.categories, name=‘name’) but I was having issues with it not being in the bot cache where it would return none and hoping this would fetch it if the get_ returned None
ah no it can't really do that
So I’ve discovered 😂
Isn`t get or fetch already trying to fetch it?
you could use guild.fetch_channels to fetch all and then use get
yeah but you can't fetch by name
Hmmm. I’ve got a temp set up with a db with the ids stored. But it’s clunky and I’m not a fan
what do you actually do with the category?
Create channel inside of the category
Nope. Purely custom for community I’m in. In theory max number of server would ≈35
that's very strange then yeah
can you see if it's there when you print guild.categories
Yeah. It was very odd. Set it up in 1 server. No issues. Expanded to 3 and it broke
It is
The last time I checked at least
are you 100% sure the name is exact
Yup. I deliberately asked to set the stuff up in each server for that reason
Case and spelling are identical across servers
hm tbf doing it by ID is far more reliable anyway but strange case
Yeah. I just don’t like having to store them in a db as for a bot of this scale it seems an over the top solution
And interms of scaling the way I have it set up is a pain as I’ve got to add the ids manually
(Few role ids aswell as they differ by spelling across servers)
Those look like normal options
Here's the slash options example.
autocomplete is dynamic while choices are static.
How do I get a user's public flags as an integer?
yeah
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
class lfgView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View @discord.ui.button(label="Join", style=discord.ButtonStyle.green) async def join_button(self, button, interaction): message = await interaction.original_response() print(message.id) await interaction.response.send_message('hey', ephemeral=True)
Produces an error on message = await interaction.original_response() when I press the button:
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
This button is attached to an embed that is a response to a slash command. I'm trying to access the message id of this embed.
you can use view.message for the message.
It works the first time, but after the message is edited, it's saying: AttributeError: 'NoneType' object has no attribute 'id'.
interaction.original_response gets the first response you made to the interaction, not the actual message it came from. You're looking for interaction.message
How i can send a message via webhook in thread?
i'm trying to initiate snowflake and insert id of thread in it, but i getting TypeError: Protocols cannot be instantiated
python ver 3.11.2 and py-cord version 2.4.1
Solved. I've created a model with "id" property and used it.
Can I make buttons work even after bot restart if yes how?
btw this error should be gone on the master branch
Thx
Does the library force Guild.filesize_limit to be 8MB when the boost level is 0 or whatnot, or is the API still returning the old 8MB cap?
I just uploaded a 25MB file despise the FS limit attribute being 8MB, so
it was updated to 25 on master
Ah
👀 are we all behaving here
I'm interested in how larger, professional bots setup their bot and organize their code. Are there any public, open source bots running on pycord?
not many large bots are open source, but go through https://github.com/Pycord-Development/Pycord-Manager
thats a pretty decent structure
also look out for stuff in #creations
awesome, thank you
Is there a way to make the bot stop showing “sending command” even if I still have some of the command stuff running?
no
Sending command is when discord is sending the command (ironic) not when the command is being processed by your bot
^
its discord's way of making you think the bot is already processing it but its to cover up their slow ass slash commands
I have it using delete_after, is there a way to make it still delete but not show sending command
Girl. We just told you can't remove it. It is a Discord thing
i want to execute some operations for all options of a command by using for, but i don't figured out how.
inside of Quantity function gotta be the str value of the option that will entered who using the bot
this is wrong on so many levels
yea i'm a sleepy adhd rn forget about the goofy i = i.real in for 💀 just wondered how can i manage my all options with for
-
options are typehinted, not assigned. so
opt1: str, opt2: discord.Option(...), ... -
your last 4 options are string type but default value is an int or a float?

if you want them to be inputed as integers, why not give the input type as integers, and then convert to str -
you should typehint
ctxwithdiscord.ApplicationContext
and now for your actual issue
4. have you tried "reading the docs"
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationContext.selected_options
sorry if this sounded rude 
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
oh damn i didnt even see that thing 💀
omg i gotta go bed so bad 💀
yes lol
it's ok for 2nd one btw, i did them on purpose, they're str for if someone give inputs in SI unit inputs like 10m 5k etc. i'm trying to convert the str SI inputs to floats in for already
ah alr
thank you so much btw 
The good ending 
np lol
- my god what's the variable assignment, its hurting my eyes
- why do you even set variables in the command callback when they don't depend of it and then you use them as a button callback
- you should subclass views and not do that
mb g
get_user isnt returning anything:
code:
for player in players:
print(player)
user = bot.get_user(int(player))
print(user)
await user.send(f'Your role is: {roles_assigned[player]}')
Output:
384449598305075200
None
then the user isn't cached
you could use get_or_fetch_user https://docs.pycord.dev/en/master/api/clients.html#discord.Client.get_or_fetch_user, or try doing it by guild.get_member
thanks
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 39: Application command names must be unique
i want to know what command name is not unique
how to fix that?
Sorry that's not possible
How do i add a description for link?
@bridge.bridge_command(description="To download videos from tiktok")
async def tikload(self, ctx, link):
Import Option from discord.commands and do description=""
Here's the slash options example.
@still helm ^
No lol 
thank you ! But it´s a bridge command
it still works for bridge
yeah i got it with async def tikload(self, ctx, link: discord.Option(description="xxx")
Other way around :)
from discord.commands import Option
wait does that even matter?
Does slash command have check decorators?
I think they do
hello, i want to make a "your message has been sent" bot
@bot.event
async def on_message(message : discord.Message):
if message.author.id != "1099713203413463162": ##<= ID of the bot
await message.reply("Your Message has been sent successfully")
else:
pass
@proud mason do you know smth?
Idk what you are doing, up ids are integers, not strings
oh lmao
How to create a private thread?
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command()
async def goodbye(self, ctx):
await ctx.respond('Goodbye!')
@discord.user_command()
async def greet(self, ctx, member: discord.Member):
await ctx.respond(f'{ctx.author.mention} says hello to {member.mention}!')
@commands.Cog.listener()
async def on_member_join(self, member):
await member.send('Welcome to the server!')
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot
Can bot be changed to client without issue? I'm just used to using client instead of bot
If i make 2 cogs have the @commands.Cog.listener() for example on_message will they override each other or will they run independently?
client is bad practice when you are actually an instance of bot.
that's fair
they will override each other but you do something like this:
@commands.Cog.listner(name = "on_message")
async def on_message1(...):
@commands.Cog.listner(name = "on_message")
async def on_message2(...):
even in different cogs?
oh nvm then. DIfferent cogs shouldn't override
alright
any way to schedule one-off tasks? like i want X to happen at Y time?
or create a new loop while the code is running? like i want X to happen every Y hours?
you would be interested in ext.tasks
.rtfm ext.tasks
uh
@errant crane help
ig just look it up on the docs page
should be there under the ext heading
in create_thread, pass type as ChannelType.private_thread
https://docs.pycord.dev/en/master/api/models.html#discord.TextChannel.create_thread
Okay, and how do I add specific user to the thread?
ya i see that i can define tasks.loops for my cogs. but i wanna have users schedule tasks while the bot is running. any way to add tasks.loops to my cog while running?
you can start the loop in a command too yk
Do I have to make an entire MyView() etc class to properly wait for a button press or can i do it in a simpler way?
subclassing is the simplest.
no idea what that means
all i wanna do is have a button, and when that button is pressed, do 1 thing
do you know what object oriented programming is?
i do
but i dont see why i need an entire class, and why you cant just attach a function call to a button press
Plus I am doing this entire thing in a cog which is all one big class so i have no idea how i'd properly put another class definition in there so it works
well, you asked for the simplest.
yea, well, how do i do it then
create a button, create a callback, set the callback attribute to your callback then add the button to the view.
i tried this, but it just instantly executes the callback
I'm very new to interactions anyway lol, last i made bots in discordpy was 3 years ago
Callbacks are coroutines aka async functions
and that tells me what
Here's the confirm example.
that youre doing it wrong
trying to copy that rn, but apparently its not possible to do this as it says label isnt defined
Do you know basic python?
i do but i am tired, and i did never work with classes much
self.label
same here
i have been trying to figure this out all night
All i need is a singular button with a dynamically created label, that does 1 thing when pressed
and the thing its doing also needs to be dynamic
and i cannot figure it out
can someone confirm i'm not overcomplicating this lol
but i'm already in a subclass, wut
oh, wait
i said the button
class MyButton(discord.ui.Button):
def __init__(self, customlabel):
super().__init__(label=customlabel)```
just read what you said, but, would this work too or should i just do it your way
and I'm sorry, I'm just tired and going right into interactions lol
im not stupid
Okay, i'm trying to do it the way you are doing, but now i'm unsure how to do the callback right since i'm subclassing button
this would actually work if you do self.button_callback.label = label
is it better than this tho
I just wanna do it the best way lol
eh they're accomplishing the same thing, if you want to add more custom stuff to button then i'd recommend subclassing but if it's just this one label then you could keep it down to view
i really just need a single button (dynamic label, i can do that) that also has a dynamic callback (this is what i have been stuck on for ~2h)
in what way is it dynamic
sends a message that depends on what was said in the very original command
e.g. i do /command user1
the callback needs to basically reference the user1 argument in that command as well as the original command user
right, so you've already been adding arguments to your subclassed view and assigned them as self variables
you can just keep doing that
then inside your callback, just reference self.uid or whatever you've set
currently i have 3 different implementations all at once lol
subclassing looks cleaner 
no not in the decorator
well, says it in the send_message too lol
oh the args should be self, interaction because it's in a class
well, then how do i make the label dynamic :>
if you want to do the label without subclassing button, leave a placeholder string inside the decorator and inside init do self.button_callback.label = label
because it's a decorator, it's self, button, interaction
just to make sure, like this? 
mhm
but why the button there
so you can access the button object
💀 that made it work but i never even used "button"
yeah but it's there 
magic
just because i wrote button there it works
well, thanks a lot, finishing my planned feature should be like 10 more minutes lmfao
One more issue
Despite me doing it correctly and everything working, it says "interaction failed"
is this your final callback?
wdym final callback
well
i added about 60 lines of code to my callback lmfao
but, no, the very last line is ctx.respond
could you show the callback then
Is pycord support voice recording
The code is messy, it allows you to basically keep up an infinite loop of embeds that have buttons, which create embeds with a button, etc.
But this is the only thing that actually does something "back" basically
wait, what about interaction.response.send_message
you have to respond to the button's interaction
that callback is the only issue here
perfect
now i just need self.disable_all_items to work 
if you use disable you need to edit the message with the new view
...
though note the examples there may not be 100% accurate
suboptimal
what were you trying to set LOL
forgot a positional
i love whenever an object gets printed
i find it so funny
this is just python at this point but what in the fuck does it want me to do
it's basically just a styling convention, i.e. if interaction.user not in self.members
but either works
python conditionals are half english
kind of weak that it doesn't even offer to replace it for you though
I fully figured it out
If you wanna admire it in it's full beauty, https://github.com/MiataBoy/Paw/pull/6
I am mentally dead after this lmfao
typical vscode
what would you rate this
umm hey so, for some reason this cog isn't working.
import discord
from discord.ext.commands import Context, Cog, command
class Ping(Cog): # create a class for our cog that inherits from commands.Cog
# this class is used to create a cog, which is a module that can be added to the bot
def __init__(self, bot): # this is a special method that is called when the cog is loaded
self.bot = bot
@command() # creates a prefixed command
async def ping(self, ctx: Context): # all methods now must have both self and ctx parameters
await ctx.reply('Hello!')
@discord.slash_command() # we can also add application commands
async def ping(self, ctx: discord.ApplicationContext):
await ctx.respond('Pong!', ephmeral=True)
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Ping(bot))
It's being registered like this,
class Handler:
def __init__(self, bot: BotClient):
self.bot = bot
for cog in generate_cogs_list():
print(f"Loaded {cog.replace('.', '/')}.py")
self.bot.client.load_extension(cog)
class BotClient:
def __init__(self):
self.client = Bot(intents=Intents.all(), command_prefix="!")
@self.client.event
async def on_ready():
print(f"Logged in as {self.client.user.name}")
Handler.Handler(self)
def run(self):
self.client.run(getenv("DISCORD_BOT_TOKEN"))
cogs must be loaded before on_ready
oh
...also that event definition is very off
I know
remove the @self.client.event and unindent it one level
would it work tho?
wait....
class BotClient:
def __init__(self):
self.client = Bot(intents=Intents.all(), command_prefix="!")
```???
i recommend reading https://guide.pycord.dev/popular-topics/subclassing-bots/ for a better idea on how to subclass
I'm a java guy and this is not how annotations work there
so i am a bit confused but thanks
allgood
I got one more question
I got my slash command working
but not the prefixed command
Does discord.Bot also include the commands thingis?
oh yeah you need ext.commands.Bot for prefix
Would it also suppose application command?
❤️
and discord.Client is no commands
is ping in the cog or
Yes
can you show the full cog
Do I change it to a bridge command?
you can set a different command name by including name=... in the decorator
you can also use bridge commands if you want yes
need to make sure you're using bridge.Bot too
hey guys what the code in pycord to the this (its in discord.py) - message.channel.id
the same
doesnt seem to work its underlined yellow
.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.
can I show you my code?
yes
I don't see where you defined message
yes I have just realised that any idea what I should change it to?
Is there a way to create a default setup() method for cogs?
btw
@client.slash_command(description = "Discord Ebay Viewer Command")
- async def ebay_view(interaction: discord.Interaction, url: str, views: int):
+ async def ebay_view(ctx: discord.ApplicationContext, url: str, views: int):
It's annoying to register a simple class for every cogs
why?
if this then ctx.channel.id
Umm is there something like reflections for Python?
So that, I can read every class that extends cogs
and do a automatic bot#add_cogs
Nothing but just to ease
well, this is just the conventional way
this helped me out thank its working now
How can I set default value to a slashcommand option through context
like setting a default value of option "channel" to "ctx.channel"
set it to None and handle it in callback
channel = channel or ctx.channel?
How do I make a slash command help
I dont want ilke a regular help command
I want it to be a slash command
I havent used cgs
pls tell me there is something
channel: discord.Option(discord.Channel, default = None)
No in call back
Make it yourself. We didn’t make a native implementation because all the commands are listed in the UI.
yeah that syntax seems right
wait I need to use the
I mean I need to do the redundant method
oof ok
Is there something similar to Cogs for button handler?
I think discord.ui.View is memory based only right?
im having trouble getting all members in a role
im using role.members but it only returns one person or two people in the list
its also saying ctx.guild.members is just me and the bot
Views can be persistent yk
Here's the persistent example.
Enable members intent
hello, if there are some advanced python user here could you please have a look to #1099926878451679244 ?
oh yeahhh that makes sense
hey guys, is it possible to detect who has update emoji?
audit log event
oh i guess that doesn't exist on stable yet
yeah, audit log events are not released yet
thanks
well if you really want you can use them on master
Some of my shards reset from time to time, is there any way to find out why this is happening?
The traceback or something like that.
Wdym "reset"
It's normal for a client to disconnect from the gateway after some time, discord will then reconnect it
Disconnecting and reconnecting
Then yeah that's normal
I recommend setting your logging level to INFO https://docs.pycord.dev/en/stable/logging.html
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
This'll print whenever it disconnects from the gateway etc
I will try activating it to see if there is a problem that I am causing.
But I'm reassured to see that it's normal.
Thank you very much.
is there a way to detect what was typed as an argument?
for example i have /command object:str type:str, if object:option1, i would like to have a specific autocomplete for type:str
sorry if this doesnt make sense as much 😔 (i might add an image to get my point across)
Here's the slash autocomplete example.
@edgy coral
tysm! (i completely ignored the first command 💀 )
Hey, does py-cord support setting default_member_permissions at all? Because some of my commands do show up by default to everyone despite being directed towards administrators only (I still put internal checks in, so unauthorized users get a denied message)
it should yes
(Paginator, py-cord)
does it work if you press a button, for example, that you are then forwarded to a specific page
you could add your own button that does this. iirc, there is a goto page method
you can also ask this in https://discord.com/channels/881207955029110855/1047189308131508306
anyknow already encountered "Can't keep up, shard ID None websocket is 13.9s behind." ?
Sync apparently ignores dm_permission too I am crying
you might have a blocking function in your code
I did everything in async mode, https://github.com/ordre-noir/ccc-assistant/ the code is open source. everything happens in cog.py file.
If you can point me the line, I would really appreciate I spend the day trying to find the "blocking" function.
With this loop I update the pages from my Paginator. But after the loop has run through, my buttons disappear from my custom_view.
Does anyone know how I have to design it correctly so that the buttons are still displayed after the refresh?
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
self.custom_buttons = [
discord.ext.pages.PaginatorButton("first", label="<<", style=discord.ButtonStyle.primary, custom_id="first_button"),
discord.ext.pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.red, custom_id="prev_button"),
discord.ext.pages.PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, disabled=True, custom_id="page_indicator_button"),
discord.ext.pages.PaginatorButton("next", label=">", style=discord.ButtonStyle.green, custom_id="next_button"),
discord.ext.pages.PaginatorButton("last", label=">>", style=discord.ButtonStyle.primary, custom_id="last_button")]
super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=self.custom_buttons, custom_view=view, timeout=None, author_check=False)
async def update_loop(self):
while True:
self.pages.clear()
self.pages = await self.update_pages()
await self.update()
await self.message.edit(view=self)
await asyncio.sleep(60)
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
why are you using a while true loop?
do yourself a favor and use tasks ;)
Like this? 🙂
asyncio.create_task(self.update_loop())
@tasks.loop(seconds=60)
async def update_loop(self):
self.pages.clear()
self.pages = await self.update_pages()
await self.update(use_default_buttons=False, custom_buttons = self.custom_buttons, custom_view = await self.generate_view())
why like that?
I mean the task loop instead of the while true loop
it is already a loop
it will run every 60 seconds
you just have to do ```py
update_loop.start()
Yes I just had a thinking error 😄
I have no other way to loop, the queue.get() is blocking. But any suggestion to improve this is welcome. I found a lot of example with While True.
yup thats a task yes
Just wondering if its possible to reset the users choice on a select menu?
e.g. the user selects something and it runs the code for it, then unselects it so they can select it again
Howdy! I am running a background task that updates all users in the discords roles..
I have noticed that the first time the for loop runs. It takes 1.5 seconds to update all the roles. Then it takes ~ 8 seconds for each member.. ANy ideas as to why?
That is probably due to a discord ratelimit
I'm not getting rate limit errors 
Or responses sorry
That I'm aware of.. D:
There's a high chance an async version exists.
Edit: the asyncio module has an async queue https://docs.python.org/3/library/asyncio-queue.html
discord do have rate limits where it jsut makes you wait for things
and doesnt error afaik
Ah
from what i remember too
That could be it then.. 
try:
guild = self.bot.get_guild()
member = guild.get_member(int(member_id))
await member.add_roles(
*[
discord.utils.get(
guild.roles, name=membership_list[membership_index]
),
discord.utils.get(guild.roles, name=rank_list[rank_index]),
]
)
await member.remove_roles(
discord.utils.get(
guild.roles, name=membership_list[membership_index - 1]
)
)
for i in [1, 2, 3, 4, 5]:
await member.remove_roles(
discord.utils.get(guild.roles, name=rank_list[rank_index - i])
)
except AttributeError as error:
logger.error(error)
Probably something to do with the last part where I remove the roles that I don't want to remain on the users
you might want to add a slight delay when iterating through users
they are doing While True ^^
and I am doing exactly the same
ccc_assistant/cog.py lines 55 to 56
while do:
artist_message: AristMessage = await self._image_to_process_queue.get()```
hey dark do you know if it is possible to reset the choice on a dropdown menu
.
I'll give that a go yeah
give it a 3-5 second delay between users and see if that slves your issue
you can possibly lower it to see where the sweet spot is
Well I asked it to wait 2 seconds and it too 2 seconds off the " delay"
But over all it still takes the same amount of time
What
can the task be stopped and re-triggered base on user commands ?
Yes.
for example the user clicks on a choice in the selectg menu and then it runs the code and resets the choice
as if the user never clicked anything
i cant find anything in docs or google about it
It has .start() and .stop() methods
Here's the background task example.
@silk spindle ^
edit the message with the same view again
it's scuffed but it's a client thing so you can't actually reset it without overriding the view
k i will check, thanks
is there any way to pass arguments to the task ?
alright thanks
can i just set a loop to automatically edit it with the same view every ~60seconds or would that not work
as i dont know how id refer4ence the mesage from the interaction response
you theoretically could if you tried to subclass or something, but you'd be better off running it in a cog and using self variables
either:
- 1st response:
interaction.response.edit_message - Anything after that:
interaction.message.edit
ah alright i didnt realise you could do that
so i'd just do insteraction.message.edit(view=dropdown())
Hi there!
I have a little problem,
I connect the bot in the channel but when I play a sound the bot tells me that it is not connected.
This problem occurred after it tried to talk in an AFK channel, I don't know if it can come from there.
Any clue?
discord.errors.ClientException: Not connected to voice.```
what is the py-cord version?
py-cord 2.4.0
update to 2.4.1
Fixed problem 
Is this a known issue on this version?
#library-updates message
yeah a bit neater now
I like it
basically discord did a breaking change for voice clients so every version below 2.4.1 can no longer connect
(technically this change actually existed for ~a year prior but most libs didn't implement it)
My bot worked 1h and then impossible to play a sound, in visible reason it stopped working.
I would never have thought of this update.
Is it possible to make a paginator persistent so that the buttons etc. still work after a restart?
Because a paginator has no attribute custom_id which I would need or?
I have tried this but I always get the message that "NoneType" is not editable.
Do I have to cache the message await paginator.send(ctx) with the Guild_ID, the Channel_ID and the Message_ID here and then read it again at the bot.ready event so that I can find the message?
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
for guild in self.bot.guilds:
self.bot.add_view(await PaginatorInfoView(self.bot, guild.id))
paginator = await PaginatorInfoView(self.bot, guild.id)
if paginator.task is None:
await paginator.start_loop()
self.persistent_views_added = True
@commands.command(name="show")
async def page(self, ctx):
guild_id = ctx.guild.id
paginator = await PaginatorInfoView(self.bot, guild_id)
await paginator.send(ctx)
You should call super().__init__(timeout=None) inside the view __init__ method
This is my supper().__init__ but when I restart the bot the buttons of the paginator don't work any more.
super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=self.custom_buttons, custom_view=view, timeout=None, author_check=False)```
I have just realized I have the same problem
Issues so far:
dm_permissionflag ignored on@slash_commanddecoratordefault_member_permissionsignored when set after command definitionpersistent views are not persistent
You should also call bot.add_view(MyView()) when on_ready is called
In your case you have to instantiate the whole object with parameters
I have not yet figured out how to get a Paginator persistent.
It is said everywhere that the paginator class behaves like a view but you can't assign a custom_id to the paginator class and with bot.add_view(MyView()) it doesn't work either.
When I try it this way I always get this error because it doesn't know what message it is because I can't assign a custom_id like with buttons etc..
await self.update(use_default_buttons=False, custom_buttons = self.custom_buttons, custom_view = await self.generate_view())```
AttributeError: 'NoneType' object has no attribute 'edit'```
How do you mean exactly?
I don’t know either
I am now trying to figure out how paginators work and how to set custom ids on them
Here, however, it is output that persistent = True... 🤔
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
for guild in self.bot.guilds:
self.bot.add_view(await PaginatorInfoView(self.bot, guild.id))
paginator = await PaginatorInfoView(self.bot, guild.id)
per = paginator.is_persistent()
print(per)```
You are awaiting a constructor, is that supposed to be?
Yes
per outputs with True but I still get this error because it probably doesn't know which message to update which is supposed to happen via the custom_id 🤔
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
for guild in self.bot.guilds:
self.bot.add_view(await PaginatorInfoView(self.bot, guild.id))
paginator = await PaginatorInfoView(self.bot, guild.id)
await paginator.update()
per = paginator.is_persistent()
print(per)```
AttributeError: 'NoneType' object has no attribute 'edit'```
Also you are instantiating the same object twice
https://github.com/Pycord-Development/pycord/blob/master/examples/background_task_asyncio.py I really struggle. Trigger a background task using arguments from a command.
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/background_task_asyncio.py at master · Pycord-Development/pycord
I'm not exactly sure how you set it up. But you could have a dict mapping the argument to the task and than just do something like this
tasks[argument].start()
I do not know how to solve this correctly
Can I get the name of a members rank? I want to check if the member has a rank to skip updating it..
role.name() for role in User.roles
AH, nice thanks!
If I’m subclassing my bot, is it possible to define slash commands within the class? If so, what would that look like and how would I specify kwargs without the decorator being present?
If I understand correctly, ctx.defer() is cnsidered a reply to the interaction
because i am not able to do send_modal afterwards
i faintly remember reading that the @discord.slash_command decorator works in Bot subclasses
Ahhh, so I use discord instead of an instance of bot
yes thats correct
if you really want to send a modal after deferring, send a button that sends the modal
hey, this is a very simple and dumb question...
but I have been seeing places where the bot mentions the number of lines of code it has been written in.... any idea how can I do that too?
I can make the embed and stuff... I just wanna know how can i count the number if lines of code in a repo
i know the readlines() and len() methor
but like is there any round the way i could do it for all files all together? like cog files, json files and others?
Iterate through the files get the count and add it to a counter?
Make sure you do that at startup and not everytime the command is called though.
There is no way of getting the guild of the interaction?
interaction.guild or ctx.guild
If you would type hint it should show up automatically
I did it but it didn't show up so i thought it wasn't a thing, sorry.
if i have the direct link url to an image, how can i send it to discord?
copy and paste?
await ctx.respond('https://zapquaker.netlify.app/img/card.jpg') if i use this, it sends the image, but also the url
anyway to send just the image and the url text doesn't appear?
you could download it and send it
Can I send the ephemeral message to a specific user instead of me?
await ctx.response.send_message(embed=embed, view=RateButtons(self.bot, user), ephemeral=True) ```
do you mean per dm?
Only the user that made the interaction (used button, ran command, etc) can get an ephemeral message
what the heck is this error?
code:
def write_json(path: str, data: dict | list):
with open(path, "w") as f:
json.dump(data, f, indent=2)```
exception:
Traceback (most recent call last):
File "main.py", line 3, in <module>
from classes.settings import Settings
File "/home/bot/bots/service_droid/classes/init.py", line 1, in <module>
from .settings import Settings
File "/home/bot/bots/service_droid/classes/settings.py", line 3, in <module>
from ios import read_json, write_json
File "/home/bot/bots/service_droid/ios/init.py", line 1, in <module>
from .json import read_json, write_json
File "/home/bot/bots/service_droid/ios/json.py", line 10, in <module>
def write_json(path: str, data: dict | list):
TypeError: unsupported operand type(s) for |: 'type' and 'type'```
what is data?
a dictionary or a list
but it already failed at the import
found the problem: wasn't using my venv and with that also not 3.10, which adds the feature with the pipes
How can I send a DM message to the message author?
at what?
huh?
Yeah I have a command, i just want it to send the response via dm, and not as a normal message in the channel the command is ran
ctx.author.send
thanks
If I subclass my bot, are there any security concerns with storing the bot's token as an instance variable of the bot? (And by concerns, I mean glaring concerns; this bot won't be very public)
As long as no one else is accessing your code, no
If you for some reason have an eval command, just make sure perms are setup correctly
Gotcha, thx 👍 And by eval you mean a Python eval and not a Bash eval, right?
Mhm
Is there any clean way to check if a user defined guild ID is valid without the API throwing an error?
I currently have this, which prints my custom error, but the API still prints its error:
# Check that guild_id is valid
guild = self.get_guild(self.guild_id)
if guild == None:
print(f"ERROR: Could not find valid guild with ID: {self.guild_id}")
await self.close()```
I also attempted to do Try/Except, but the API error was not caught.
Not really
Fair enough, thx ❤️
Am I?... (honest question) I'm ultimately just trying to input guild_ids for the @bot.slash_command decorator. I currently have the end-user define an environment variable with the ID of the guild the bot will join, but am struggling with input sanitization.
Maybe there's a better way to do this?
I feel like it's chicken-in-the-egg, because I need the guild id from the bot, but the commands get defined before the bot instance exists
yeah you can't really validate it without making a request
is this for a custom command system
And there's no way to obtain the guilds the bot is in before defining its slash commands?
not the way pycord is structured, no
it's technically possible to resync commands even after the bot is connected, however... it's kind of been broken here because of a rather annoying design flaw
So my premonition of it being a chicken-in-the-egg issue is actually correct. Damn, that's too bad, but I can ultimately deal with it for my application. Thanks! 🙂
I have the following two files:
main.py
import os
from dotenv import load_dotenv
import discord
from src import MySubclassedBot
GUILD_ID = None
def main():
COGS_LIST = [
"CogCharacters"
]
# Load environment variables
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
global GUILD_ID
GUILD_ID = os.getenv('GUILD_ID')
bot = MySubclassedBot(TOKEN)
# Add cogs to bot
for cog in COGS_LIST:
bot.load_extension(f'cogs.{cog}')
bot.run(bot.token)
if __name__ == '__main__':
main()
cogs/CogCharacters.py
import discord
import main
print(main.GUILD_ID)
class CogCharacters(discord.Cog, guild_ids=[main.GUILD_ID]):
# Stuff...
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(CogCharacters(bot)) # add the cog to the bot
I'm just trying to get GUILD_ID from the main function to the cog py file so it can be used in the class definition. I feel like this should work because main should be called and executed before Python even knows the cog file exists, but print(main.GUILD_ID) still prints None. Does Python get pre-compiled to byte-code? Maybe that's why the class is created before main() is run?
import main will create a completely new instance of main. Since you imported it, __name__ == '__main__' isn't True so main() is never run.
ultimately you've overcomplicated it, you can just use bot.get_cog to get the class and set cog.guild_ids
Omg you're a life saver... This makes so much sense, is way easier, and I learned something new about importing (well, I already kinda knew, I was just being dumb 😅 )
yeah gotta understand importing first
what you were trying to do would have normally lead to a circular import
never let files import each other
I didn't think main.py was importing the cog, but I guess the API function load_extension kinda does that, doesn't it?
well that's what i meant by normally, load_extension is designed to work around imports but if, for example, you weren't using this lib it could be something like ```py
main.py
import os
from dotenv import load_dotenv
import discord
from src import MySubclassedBot
from cogs import CogCharacters
bot = MySubclassedBot(TOKEN)
cog = CogCharacters(bot)
...
CogCharacters.py
import discord
import main # instantly error on this line```
since import main would then do all the imports in main, which would lead to doing all the imports in CogCharacters... and so on, an infinite loop so python just says no
Gotcha. Makes sense. I think I just went down a rabbit hole and started spaghetti coding, lol. Thank you very much for helping me on my journey to get gud at Python 😅
you could also just do it in the setup function of the extension
yk like
def setup(bot):
cog = MyCog(...)
cog.guild_ids = bot.some_attr
bot.add_cog(cog)
Thank you for posting this. I just came back to report the following didn't work to immediately force the commands to be cached in the guild, but what you posted should because the field is getting set before add_cog
# Add cogs to bot
for cog in COGS_LIST:
bot.load_extension(f'cogs.{cog}')
bot.get_cog(cog).guild_ids = [GUILD_ID]```
So, I'll try your way, which should work 🙂
how the commands cannot be used by the specified user to be like this, as my knowledge i can hide the command (which is the thing that i searching for) if the channel that command begin used for is NSFW or guild_only for e.g, however, how it can be selected for a user or role :\
idk if it's one of the (default_member_permissions) or (checks) Attributes :\
That's default member perms
i will "TRY AND SEE" :)
huh, someone forgot a todo task :)
I'm having an issue which seems to be pretty common but I can't quite grasp the solution, or why it works. I am trying to delete an ephemeral message upon the user interacting with my view, but regardless of the method I use, the message is not found
obviously we know the delete() method doesn't work on ephemerals, so I went for delete_original_response(), which seems to timeout after a few moments of not finding the message
you want interaction.message.delete
yeah that's the one I tried first
class ConfirmView(discord.ui.View):
@discord.ui.button(label='Submit', style=discord.ButtonStyle.green, emoji='✅')
async def submit_request(self, button, interaction):
await interaction.message.delete()
that's working fine on my end

it works with ephemerals because discord added support for it months ago
I didn't know that, that's a good update, but nonetheless I can't seem to delete it
hmm
delete_original_response is for deleting responses you do with response.send_message, not the original message
if it's not working then there's a chance the user already dismissed the message
if any additional context will matter, here's where the view appears:
await ctx.reply(embed=embed, view=ConfirmView(), ephemeral=True)
upon calling a command of course ^
I'm absolutely baffled
does anyone know how i can get a member object through an id because my view class is outside the setup function in the cog and i need so send an message to a user with a button
iirc, that works if you defer and then use it
@plush meadow can you try that?
Defer first and then use delete original response
let me give it a go
guild.get_member ?
works perfectly, care to explain why that works? just trying to understand better
that seems like a bandaid fix, but perhaps it's not and i just don't get the inner workings
oh it's not actually a bandaid, discord considers it intentional
i mean visually it works flawlessly, but this is itching my head since Nelo mentioned interaction.message.delete() is supposed to work as intended
i forgot it's because the standard endpoint doesn't work with it nicely
oh, i see
i mean if that's the proper way to write it, i'm more than satisfied. thank you both for your help!
i tried but if i safe it in a variable ne variable is empty
user = interaction.guild.get_member(id) doesn't work
Can I use this to add and remove roles at the same time?
Currently I am adding a role from a list, and the. Removing all others in the list from the user.
This seems to result in discord timing me out for a couple seconds… so updating a list of 8 users takes 50 seconds
if you have a complete list of member roles, you can edit that list and use member.edit to edit all the roles at once
https://docs.pycord.dev/en/master/api/models.html#discord.Member.edit
this is also doable with add_roles and remove_roles if you set atomic=False, it'll be a single request
so this is a thing with message components. if you defer the response, discord considers the message on which the item was attached to, as the response. which allows you to do some interesting things.
the most important one, is that you dont need to send a followup, unlike app cmds
secondly, the edit_original_response and delete_original_response endpoints now point to the message the item was attached to
so that allows for your use case
it could be possible to say that, if you send any response other than response.send_message, the attached message is considered the response (cases like response.edit_message or response.send_modal). but im not sure about this
Hey guys,
Is it possible to send a modal to a specific channel which was given by a slash command?
So /command <channel> -> Getting the id -> Opening Modal, then filling it -> Sending the content to the channel what I give in the slash command
do you mean an embed?
you can't "open" a modal in another channel
it'll just popup wherever the user currently is
you have to open a modal with an interaction
So yes, basically I want to send an embed to the channel I typed in the slash command, but I want to write the content with a Modal, then send the embed to that specific channel
Yes, I've made the Modal class
then you're more or less done
assuming you've overridden __init__, add another argument for your channel
then assign it as a self variable and use it in your callback
Alright
Would someone be kind enough to demonstrate how I'd make a view persistent on restart? Views are a bit confusing to me in the first place so the docs are a little unclear for me.
I've made my timeout None already, but I'm having a hard time figuring out where to stick the persistent boolean
There is not persistent boolean that you set. Views are automatically persistent if they have not timeout and all items within them have a custom ID.
really? I could have sworn I remember something like that
let me give it a go and see
Here's the persistent example.
This can help if you have not seen it yet
ah okay wait, I am not adding anything in my on_ready() listener
so I just have to add the view itself, and all the messages which utilize the view will automatically work again?
and no I had not seen this, thank you very much
Okay, managed to do what I wanted, but when I submit the modal, it doesn't close itself. I didn't get any error message in the log, only Discord tells me something went wrong.
did you use response in the callback
you have to somehow respond as well as do your other logic; either by send_message, edit_message or defer
Ohh, I didn't. I responded for the command within the command, and not inside the modal class. I fixed it, now it works perfectly 👌
Thanks for the help, really appreciate it 👍
So I feel like I'm very close to getting persistent views to work, save for one issue. My buttons are dynamically loaded, they are not hardcoded into the view. So when "caching" them, I can't just send a blank view with no buttons. That being said, in the example, it mentions that # In a more complicated program you might fetch the message_id from a database for use later. I am actually already saving these messages in a database, so what's the recommended way of caching them via message ID? the example doesn't explain that part
I am referring to the prepare() coroutine in the example at line 68
Is the tag botvar encouraging bad practices? Shouldn't sub-classing be encouraged instead?
Just wondering... When did client.load_extension become async?
well you aren't if it's async
hey is there anyway to get a members activity status?
probably member.status
🤷♂️
im looking it up but im only getting member.activities[0].name
which gives me a empty tuple
hmm... yup. Somehow my dependencies got discord.py in them... Lovely.
Thanks 🙂
wouldnt that give me the status not the activity?
what kind of activity/statuses are you looking for
like the names you can put with a status
custom status?
yeah
i think that isn't available on api
hold on
theres threads on it so im guessing it has it
ok yeah it's under activities, didn't realise discord threw away my status again
but you probably need the presences intent
so i dont need the list?
?
so why when i use activities[0] its out of range?
though i think activity just returns the first one
does your bot have the presences intent
it has all
i actually only need the main activity
so maybe the first solution would work
is there any clean/kosher way to remove a bot from a server from the backend?
my use case is: I provide a paid product and one customer has ghosted me. the bot is still on their server. Can i remove it somehow?
i have blocked them from doing anything with it but it's still there in the list and consumes 'some' resources
.rtfm guild.leave
get the guild object using bot.get_guild
appreciate it
np
is there a way to disable the debug, I haven't installed or enabled anything and this started spamming the console
Fixed it
Please.... Please don't say fixed it... SAY HOW YOU FIXED IT
Why do you even use logging?
↑
uh yea but if you gonna host more than one bot it can be annoying
I use pm2 and it would spam the pm2 logs
just log to a file then
↑
I just make it overwrite everytime my bot restarts
and I'm not saving Debug in just doing Info
Debug will probably need a lot of space very very soon
For a small application
dpy? 
yes?
||this is pycord.... but that thing is the same. so you are lucky||
Does anyone know if you can just have 1 slash command group because the commands from my second group won’t register
you can have 100 top level slash commands/groups. (not talking about subcommands and subgroups)
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)?
A thing I never understood; why use bot.commands in main file but discord.commands in a cog.
Why not just use self.bot.commands or discord.commands in both. 🤔
what?
cogs use discord.commands
wdym
isn't it just @discord.slash_command
yeah or that.
Nonetheless the discord part
Why is it bot in main file and discord in a cog
Why not just make them both the same
And use discord
because in the main file, how do you know what the bot object is otherwise
in the cog, you are provided with the bot object
that doesn't work because self is not defined
in a cog it should be in the init... No?
decorators aren't inside a function/method.
making it static would cause... more problems
kk tyvm
yw
I just named the group exactly like the cog class name that was the problem
How can I get the context from an on_message event?
context is only generated for commands, not for every message
what are you trying to do?
Ah, ok. I'm trying to do async with typing in an on_message event
pretty sure you can do that using async with message.channel.typing(): or smth
.rtfm channel.typing
yep
Oh, ok. Thanks 😄
Context just provides shortcuts to these methods. You can do almost everything without it
Oh, ok. Well, thanks, it works now 🙂
nice
Is there any quick way to prefill slash command options made with bridges?
e.g. i wanna have a field with 2 options, how can i make it suggest these 2 options automatically?
I launched my bot today and it started to print out an bunch of debug info after updating pycord what da hell?
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
Becouse cogs are not apart of the discord bot until you use bot.load_extension
Are you on master or latest release?
The latest pypi release
yea, i read that, but i have no idea how i have to pass that into the @bridge decorator
Do you have logging enabled? Or a debug value set somewhwre?
This is what it prints, an bunch of info about the discord servers its in etc. This is my main startup code
Which py-cord version do you use?
Uhh just try it and i think it will work for slash commands but not for prefix. Tbh I have not used bridge.
the latest pypi release
well thats kind of the problem lol, i tried around a lot and didnt manage
Can you show the pip list?
Please may you instruct me on how to get the pip list?
Have you used the type hinting version? Or the decorator. Try the type hinting of you have not
type hinting how
currently i just made it as boolean but i might wanna add a third option later, that's why i asked
this correctly shows True and False, obviously, but i'm stuck at how to make it properly
oh wait, i think i know what you mean, 1s
Is there a way to fetch the users that are interested in an event using pycord? With discord.py it works, with pycord it’s returning „none“. And it’s not returning the creator of an event either
Okay, i am trying to switch to using the decorator to set up my slash command arguments, however I cannot get it to show a list of users like it used to
This, in the function arguments, showed it perfectly fine
AHHH 
Okay i advanced lol
how tf do i make the input_type of an option "user", i already tried discord.Member
discord.User
Somewhere you have debug level logging set to true. It might be an ide setting too. Does downgrading to pycord 2.4 change anything?
how do I get an normal Interaction if I only have the Message
messages dont have interaction 
interactions are created for each button press, app cmd run etc
What's even a "normal" interaction supposed to mean
The Message Object has an attribute called interaction which return a MessageInteraction
Here's the basic voice example.
this message is a response sent to an interaction. so it will have the message.interaction attribute
oh okay thx
anyone have an idea
it works when i just use user: discord.Member in the function arguments without any decorator stuff
why dont you use discord.Member?
try this :
Okay, wtf, that works, but only if i pass it without a keyword - why?
Shouldn't
discord.Option(input_type=discord.Member)
and
discord.Option(discord.Member)
be the same?
no bc input_type requires
input_type=<class 'str'>
so when can you actually use input_type=
I actually dont know
If I only have the Message can I give a respond which only the user who sent the message can see?
yes
add ephemeral=True
Next question, what tf does "autocomplete" take?
I tried ANYTHING i could think of
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
hello, i forgot how i can do dynamic button titles with add_item() is there any guide out there?
that would work if I have the ApplicationContext but I don't I just have the Message -> discord.Message
how do i create a permission ovewrrite
I need some help with pycord (I'm new to it).
How do I create options for slash commands? I have looked at the docs but they are very spartan and do not provide much detail in this topic. A code snippet would be nice.
a command could look like this
I appreciate you replying, thanks a lot!
I hope it helps you though
How do I set up permission-only commands?
what do you mean with permission-only commands
like commands that only people with a specific permission can run
it accepts a function
that function should have only 1 argument of AutocompleteContext
also see this
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_autocomplete.py at master · Pycord-Development/pycord
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
Can I somehow find out when a user joind via an invitation link to the server from whom this user was invited?
discord.on_member_join(member) could give you an event when a new member joins but im not sure if you can from whom that invitation is
can you try if this works?
class MyView(discord.ui.View):
def __init__(self, label, ...):
super().__init__()
self.button1.label = label
@discord.ui.button()
async def button1(self, button, interaction):
...
Yes I know that so far I have everything but I would like to somehow find out who invited the user 😄
not available directly
the best you can do is constantly track invite usages, then in the join event see which one changed
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_perms.py at master · Pycord-Development/pycord
what kind of function
the example kinda shows you already
Here's the slash autocomplete example.
oh, i called the function


