#Basic Pycord Help (Quick Questions Only)
1 messages · Page 71 of 1
oh
yeah
oof okay
your only choices are accepting mentions as strings, or doing some fuckery with autocomplete
i recoded a bit of the command now it returns an error if role and channel both are given
no way thats too much for my brain
accepting mentions as strings shouldnt be very hard
but that’s upto you
now it works perfectly fine if only role or channel is given, and operation type is removed too
it adds if its not there and removes if already there
well yeah but still ig it works this way too
class Youtube_Cog(commands.Cog):
def __init__(self, bot_: commands.Bot):
self.bot = bot_
self.command_group = self.bot.create_group("youtube", "Control youtube audio in voice chat")
@self.command_group.command()
How can I do what I'm trying to do here with the @violet magnet decorator
since that obviously isnt valid
sorry guy I tagged lol
ah nvm
this does it
This doesnt really work either
anyone know how to make slash command groups inside a cog?
found it? https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog_groups.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog_groups.py at master · Pycord-Development/pycord
Can't do anything. Discord limitation. Implement the checks in your code
how to make a filter for a valid integer which is between 1 and 100,000?
@option("level", Union[], description="The level at which a role should be rewarded.")```
Idk what to put inside the Union, idk if it's right so far
Yes that's right
couldn't find anything relevant on stackoverflow ;o
Use min_value and max_value
But wouldn't that be string input
In the option decorator
??
For string length you have min_length and max_length
Or find it in discord docs
alright!!
@option("level", description="The level at which a role should be rewarded.", min_value=1, max_value=100000)
AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number
How to change the SlashCommandOptionType
oh nvm i figured it out
i forgot to put level:int in the typehint
@stark walrus if this is a command, then the question is why do you make an exception for permisses in the "if"
if you can use ```py
@commands.#functions example has_any_role("role"),
@commands.has_permissions(administrator)
I would need to handle the error separately then
or have it respond to all such in the on_command_error event
right?
If u need respond for those who do not have administration rights
hey
@client.slash_command(guild_ids = servers, name="post-leaks", description="Postet einen Leak")
@commands.has_any_role(1073964313309614154)
async def postleak(ctx, channel: Option(discord.TextChannel, description="In welchem Channel soll der Leak gepostet werden?", required=True)):
if channel is None:
channel = ctx.channel
await ctx.send_modal(PostLeakModal(title="✨ Leak Posten"))
class PostLeakModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Name", placeholder="ws_hud"))
self.add_item(discord.ui.InputText(label="Preview", placeholder="Placeholder"))
self.add_item(discord.ui.InputText(label="Download", placeholder="Placeholder"))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="\✨ Neuer Leak", color=0xff0000)
embed.add_field(name="Name:", value=self.children[0].value, inline=False)
embed.add_field(name="Preview:", value=self.children[1].value, inline=False)
embed.add_field(name="Download:", value=self.children[2].value, inline=False)
embed.set_author(name="FlareLeaks #2,0k", icon_url="https://cdn.discordapp.com/attachments/1073964316010758206/1079478593303875614/Founder.gif")
embed.set_footer(text="Offizieller Bot by !Colin † ™ 🎾#0001 | FlareLeaks #2,0k", icon_url="https://cdn.discordapp.com/attachments/1073964316010758206/1079478593303875614/Founder.gif")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1073964316010758206/1079478593303875614/Founder.gif")
await interaction.response.send_message("> Leak wurde erfolgreich gepostet!", ephemeral=True)
await channel.send(embed=embed)```
how can i get the channel in the class that I have in the slash command?
Pass it to the modal
how?
Using the init
do you know basic python?
You should know how to work with classes if you're coding with pycord
yes but i was in vacation and need a quick fix
can you pls say me the fix?
No
Then learn python
?
We won't help you
No one will help you
#help-rules states you won't receive help if you don't know python
If you knew python, you'd know how to pass a simple variable to a class
¯_(ツ)_/¯
idk
Hello, i'm trying to send an embed through a webhook but I can't figure out where is the problem. This is the payload:
"content": null,
"embeds": [
{
"title": "Title",
"description": "description",
"color": 5814783,
"fields": [
{
"name": "Field 1",
"value": "Field description"
},
{
"name": "Field 2",
"value": "Field descriptions"
}
]
}
],
"attachments": []
}```
and it's being sent through this line of code
```py
response = requests.post(webhook, data=payload, files=files)```
Any wonders why it's not working?
Failed to send webhook: 400 {"embeds": ["0"]}
Oh I think I found the problem
i forgot the headers
Btw if you are using webhooks in your Py-cord bot, Py-cord already has webhooks built in
Okay, I tried, thanks
Why do I need to do that tho? Why I can't just create bot = Bot() somewhere and just use it and not pass bot every time?
what?
from guide.pycord.dev
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
...
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot
Why not like that?
import discord
from discord.ext import commands
global_bot = None
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): # this is a special method that is called when the cog is loaded
...
...
def setup(bot): # this is called by Pycord to setup the cog
global global_bot
global_bot = bot
bot.add_cog(Greetings()) # add the cog to the bot
Because the cog needs to use bot to register commands/events
So, can I use global_bot for that?
Or every cog need to have self.bot?
each cog needs a bot attribute
Oh, okay. Thank you
you can extract the id and access it via a variable
How
guys help, I want to prepare a little joke so that the bot would catch the user's messages, delete it and then write the entire text itself
Who faced a similar problem
Idk pls help me
@fervent cradle
chan = channel.id
send_ch = bot.guild.get_channel(chan)
await send_ch.send(message)
Thanks
That won't work lol and makes no sense on their issue
@fervent cradle sorry i have mistake, automatic ctx write 
Okay
And what's the issue?
@full basin so to speak, the muse escaped me and I’m thinking where to start using a static command without a prefix or a bot event, I don’t like messing around with events, although this is the simplest solution
I'm just looking for inspiration mostly, that's while chatting about x y conflicts, I created a code for checking messages but temporarily put it on the back burner because the hosting almost burned down at one moment 
But unfortunately, I still can’t fix a technical flaw in the game timer, with a repeated or unreadable answer, it restarts the timer, I thought about creating an exception, but maybe it will kick again game
bro why does this person sound like an ai to me
I didn't understand a thing of those 3 paragraphs
AI I am interested
looks like I've been exposed

So I sometimes host an bot in replit, not important. But is there any way I can change the server with the console
Server name I mean
So it asks me to what I want to change it
?tag norepl
Why NOT to use Repl as a hosting platform
You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You'll need a web server alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
IMPORTATNT
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.
Heya, i have question, i want create fun command/event bot take my msg, delete original and send itself
and I think how to do it in interaction mode so that the bot does not delete, but removes the message by api and send
But still my quistion, how do I make it
help
?tag replit-install
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
i have to do all these steps if i m using replit my host ?
any other free platforms to host my bot ( i m newbie so cant spend money atm)
if you are a student and have a school email, you can use microsoft azure
i m student but dont have a school email
how about github ? willl it work for hosting pycord bot ?
github doesn't host python scripts, they only host websites.
oo , pls give some suggestion for hosting
If you have a credit card, you can use railway.app or oracle free tier
If you actually want a good host, you're going to have to spend money though. Railway or Oracle will work fine for early stages.
they should be good for like the 60%-tile of bots.
Depends on what the bot is doing, but yeah, as long as the bot is small, a free host will be "good enough"
async def callback(self, interaction: discord.Interaction):
email = self.children[0].value
donate_return = await donate(
email, self.plan, interaction.user.id, type=self.type
)
await interaction.response.send_message(
f"Please pay the invoice at the following URL: {donate_return}, the link has also been messaged to you.",
ephemeral=True,
)
await interaction.user.send(
f"Please pay the invoice at the following URL: {donate_return}."
)```
'coroutine' object has no attribute 'id'
/Users/X/bot.py:222: RuntimeWarning: coroutine '_static_request_patch' was never awaited
donate_return = await donate(
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
i did await it tho?
full traceback?
i think python is trying to guess where to await
like if you had
async def func()
return "Hello"
and you did
l = await func().upper()
then python might try calling func as a normal sync function, and thinking that upper is the async function, so it awaits that
@shut jasper u use static slash with global variable?🧐
'coroutine' object has no attribute 'id'
/Users/XXX/bot.py:224: RuntimeWarning: coroutine '_static_request_patch' was never awaited
donate_return = await donate(
Object allocated at (most recent call last):
File "/Users/XXX/venv/lib/python3.11/site-packages/stripe/api_resources/abstract/createable_api_resource.py", lineno 16
return cls._static_request(```
good?
Full errors traceback 
where? thats all i get after enabling tracemalloc
then look, you have an error in higher calls because the function does not call the id (has no attribute "id")
respectively, the whole function is ignored
since I don’t see the continuation, I can say that he swears obscenely at the second variable
that's where that tip was before I emulated the pycord by hand and pushed in a couple of libraries
im confused
@shut jasper u donate_return can't see donate (vars<)
on it I had a question whether you use global variables in the code?
What port does py-cord use?
connect to network
It's a client that does HTTP communication, it doesn't use any port unless you're talking about 80 and 443, but that's literally any program that needs HTTP(s)
Is discord going to remove support for normal commands?
I mean ones we use without the slashes
Such as !help
That's literally impossible for them to do unless they completely block bots from reading message contents
I don't know. They seemed to be pushing slash commands a lot so i thought they were going to
They obviously want you to use slash commands, and it makes sense because they're way better
But they won't "remove support", because they don't have "support" for it in the first place. It's just the library parsing messages as commands and responding accordingly.
You still need message content intents for normal commands to work though, so unless your bot has a good use case for that intent, you're doomed if you ever want to verify your bot.
Verified bots can't have that intent?
You can apply for it, but if you don't have a good use case, they won't give it to you.
And no, commands is not a valid use case
i dont think so
Prefix commads works and will be works
Okay
can you show the code where you use that?
can someone PLEASE help me with the following error?:
File "main.py", line 31
^
SyntaxError: unexpected EOF while parsing
my code only has 30 lines and yet this is happening
I'm not sure if this is a repl.it error or a pycord error
You have some weird whitespace character in your code. Nothing to do with pycord
My guess is that you copied the code from somewhere and when you pasted something tried to format it and failed
I didnt
its original code
import discord
import random
import os
bot = discord.Bot(command_prefix="cmd ")
@bot.event
async def on_ready():
print(f"we have logged in as {bot.user}.")
@bot.slash_command(name='message')
async def message(ctx):
await ctx.respond("alright: \n")
rand = random.randint(1,3)
if rand == 1:
await ctx.respond(f"WHY DID YOU WAKE ME UP!")
elif rand == 2:
await ctx.respond(f"arrgh I was busy!")
elif rand == 3:
await ctx.respond(f"stop commanding me around!")
@bot.slash_command(name="thread",description="make a thread")
async def thread(ctx):
message = await ctx.respond("alright but you could have done it yourself")
@bot.slash_command(name="thread",description="make a thread")
async def thread(ctx):
message = await ctx.respond("alright but you could have done it yourself")
bot.run((os.getenv("TOKEN"))
And how did you get it into replit?
I wrote it.
ok wait there was an extra bracket
bot.run(**(**os.getenv("TOKEN"))
bot.run(os.getenv("TOKEN"))
@limber urchin @proud mason can i dm any1 of u to help me with my bot stuff ?
no
- Remember that
You can't dm help people unless they allow you to do that even staff members
You cannot ping or DM people for help unless they allow you to do so, even if they are staff members.
What part of that rule didn't you understand?
I understood the whole msg
That's why i asked for perms ig ?
^^
you don't have the perms for that
just ask here or create a new post
& the reply was no from your side 
How to install py cord in vs code
After reading the GitHub i changed my mind to use vs code
do you know basic python?
dude. It's just python. if you have the python interpreter just install with pip
I believe the new voice messages can be already read with pycord, right?
I was thinking of making a transcription command through whisper, not sure if that would work properly though
if you're on an older client you can tell.
I was on Aliucord on my phone earlier, I haven't updated it ever, I saw them as .ogg files.
They are just standard attachments, which pycord can handle.
I've seen on mobile that they're basically .ogg files, not sure if the api handles the voice messages the same way as basic files though
amazing, thanks!
One would assume they would just be standard file attachments.
I am not sure what you are trying to achieve, but you can just check if the attachment is an ogg
I simply wanted to make a command to transcribe voice messages, believe that would be useful
Yes , i have py installed in pc so confused if i need to install it in vs code as well
it's not an extension or something, it's a pip package.
? Do you know the basic's of Python?
Yes
Alright. all you have to do is install pycord from pip and import it.
how you install stuff is basic stuff
Reading documentation too! That's like basic computer knowledge kek
My friend got alot of errors & stuff he had installed multiple libraries
Alright, well is it working for u atleast
Can I make a slash command alias or do I need to just duplicate the command code and change the name?
what do you mean with alias?
Another command with a different name that does the same thing
like /lock and /close - but the command does the same thing
give it a new name
slash commands does not have an alias
So i would need to duplicate the command
how to host my bot code written in vs code
what?
why in vs code?
VS Code is not for hosting a Bot
my code is written in vs code bruh
i will use hosting provider
to host my bot
nbut how to host it like is it possible to link them or smh like that ?
Hello, I have created a task loop in my bot. And I gave it a list with 4 hours as datetime object.
However, after the bot completed its task at the last hour (02:00) in the parameter, it put the loop into an endless loop and sent the message that should throw certain hours. Do you have information and suggestions about the reasons and precautions for this?
What does this change? Bruh
vscode is just an editor, with some really nice to have tools, but your bot is never hosted in vscode.
You can use the terminal provided in vscode to host your bot but that does not automatically mean it's hosted in vscode as it is still hosted on the machine you're using vscode on.
@solemn idol @glossy tusk i m not saying that i will host my bot in vs code but i m asking that how to host my bot on hosting ( code is in vs code can i link them somehow ?)
Push py file to github.
Clone it on VDS.
depends on where you are hosting
but yea like the other guy said, upload code to github
Ok thx may i dm u if i face any issues regarding this ?
@limber urchin
that is basic python?
what u mean
why are there spaces?
@waxen whale can you get this guy to stop pinging me?
O mb typo
Ok it was first ping tho
You've pinged me 3 times buddy
Follow the rules or get out
You can't expect anyone to help you if you can't follow basic rules
Essen 
more like watching this now
lul
i m following the rules ig ? this are some basic error so i m creating a thread
y'all calm down
vs code error any1 ?
that is not a vs code error
calm down?
i mean code error in vs code
i read buddy as baby and i was rofling
😂
you can try asking the in python server (.gg/python). Their explanations should be much better than what we give here.
(This server is for making discord bots in python)
Yeah u can
print(f"Guild: {guild.name}")
for member in guild.members:
if not member.bot:
print(member)```
Now It raises an error saying I must have server intent members on and it's on.
and what is with the intents at the code?
I'm so fucking dumb ty
ye
ok it works now but it keeps saying this, is the library im using bugged?
I put manage_role=True as a default permissions, but people without permisisosn cna still see them and use them
Do you know why the default_permissions dont work ?
( it was working before I put them in a slash group)
i tried to do that, but still it let me do commands as a user without any special perms
what if you add commands.has_permissions?
i get
yes it works, it will throw a MissingPermissions errors. But this is not the behavior I wants
I want to put a default_permissions
use both
the default permissions does not work
that is my problem
it works for single commands, but when I put in groups it is not working anymore
see I have the default_permissions(manage_roles=True), but not working
I switch account to test, it is a member with no roles or permissions but i can still see and use the commands
and I just tested it, works perfectly when not in a slash group like that:
It is getting big gonna open a thread
Does the on_message event count towards discord's rate limits?
I would say no, why?
seems like you don’t understand what causes a rate-limit. It can only be caused by an API call. This means sending a message, reacting with an emoji, fetching the users, etc.
¯_(ツ)_/¯
How would I add an autocomplete option to a command in a cog, where the autocomplete function requires self as one of its parameters?
just add that function belong the class cog and async it, or make it like a normal command code (with the autocomplete function) in a new file and import that file in the main.py
however by talking about the autocomplete, as my knowledge if the ac function didn't returned anything within 3sec's and then it returns i will get 404
so how to make an exception for that error, i mean where even the expect logic will goes :\
Thanks for the response. I tried that, but how do I properly send the self variable to the function when using discord.utils.basic_autocomplete?
Here's my command in my cog (it's also in a slash command group of "character"):
@character.command(name = "view", description="Display basic info about one of your player characters")
async def create(
self,
ctx,
name: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_player_characters))
):```
I have this for the async ac function:
async def get_player_characters(self, ctx: discord.AutocompleteContext):```
Error:
TypeError("get_player_characters() missing 1 required positional argument: 'ctx'")>```
so there is a function called get_player_characters?
bro just make it like this
@bot.command()
@Option(name="str", description="str", autocomplete=the_autocomplete_func)
this function didn't return anything so you will get invalid from body or whatever else
Yes. If I did it with the decorator like you just wrote, wouldn't the same error occur where self is not sent to the function?
dont put the function in the cog class
define it above the cog class, in the global scope of the file
send the code to debug it (‾◡◝)
I could do that, but a handle to a database is created in the main bot.py and then passed to the cog, meaning it becomes an instance variable that I have to reference using self.
# bot.py
# Database Initialization
db = SimpleMysql(
host=DB_HOST,
port=DB_PORT,
db=DB_NAME,
user=DB_USER,
passwd=DB_PASSWORD,
keep_alive=True
)
# Add cogs to bot
bot.add_cog(CogCharacters.CogCharacters(bot, db))```
# cogs/CogCharacters.py
class CogCharacters(discord.Cog, guild_ids=[GUILD_ID]):
def __init__(self, bot, db):
self.bot = bot
self.db = db```
ah
you can do ctx.command.cog or smth iirc
that returns the cog instance
let me just check
augh the pain from SQL
:(
the maximum database i ever created is an json so this might be complicated ;-;
ooh! that might work!
Would the cog object hold the instance variables?
yea it is just ctx.cog
i believe yes
pog. let me try that. tyvm!
because it is the same instance which is returned
this seems to work by send the db value from your func that will be out of the class
so its now in the init and can used like self
So, would it be ctx.cog.db? Or ctx.cog.self.db?
I'm guessing the first...
:\
Follow up question... How would I access the command author (caller) in this autocomplete function?
ctx.author doesn't work 😕
Because I confused AutocompleteContext with CommandContext
check this out https://docs.pycord.dev/en/stable/api/application_commands.html#discord.AutocompleteContext
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...
Yeh, I'm already there, but it looks like it's not possible?
Oh, I thought Interactions were something completely different from bots, my b. Tyvm
Am still noob, sry 😅
Is there any way for Option choices to be dynamic like autocomplete?
I could cheap out and just return an error if the value given is not in the DB, but it'd be cooler if invalid values were prevented in the first place
how do I get an interface like this for the user variable? 👀
Like an option to select a user?
yep like the list that shows up
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...
You'll see a Type it accepts is discord.Member
discord.Member
this error what I'm talking about
how can i give an edited message a view, message and a file?
when i try to it throws
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 positional arguments (and 2 keyword-only arguments) were given```
If I'm not mistaken, then to change the message you need
await intr.response.edit_message(content="New content of message")
In my opinion it is better to use "intr" ,a "interaction" .Although you can do it like this😓
.
That's my code doesn't seem to work:
async def ban_marked_users():
await bot.wait_until_ready()
while not bot.is_closed():
banned_users = []
with open("marked.txt", "r") as f:
marked_ids = [line.strip() for line in f.readlines()]
for guild in bot.guilds:
for member in guild.members:
member_id = member.id
if member_id in marked_ids:
await guild.ban(member, reason="User is marked.")
banned_users.append(member.id)
if banned_users:
print(f"Banned users: {', '.join(banned_users)}")
else:
print("No marked users were found in any server.")
await asyncio.sleep(5)
What is the recommended way in bridge extension to restrict commands to owner only
i want to be able to include a view & a new file though, not just an edited message
You can still do that
You just need to pass content as a kwarg instead of a positional arg
If I used commands.Bot instance, will I still be able to create a slash command?
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)```
To answer your question: yes.
Hey very stupid qeustion but how to get guild id?
get_guild?
for what do you need it?
to save guild specific info
get_guild(id, /)?
U need the id to fetch the guild object
at a command?
yes
you already get the guild with ctx.guild
@bot.event
async def on_ready():
for guild in bot.guilds:
print(f"Connected to server: {guild.id}")
For example
Yes
That's the same.
But this just gives me a list right?
of all the guild my bot is in
Yes. Do you want a specific guild?
Yes
@bot.command()
async def guildid(ctx):
guild = ctx.guild
guild_id = guild.id
await ctx.send(f"The ID of this guild is {guild_id}.")
thx a lot
Ye thx
I want to set an image to an embed. I have a discord.File object of the image, but embed.set_image() only supports HTTP(S) urls. How can I send that image through an embed?
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
@drifting birch
thanks ❤️
What is the best way to trigger a the bot when AutoMod flagged a message? Is there a dedicated event or do I must filter via on_message?
.rtfm on_automod
Target not found, try again and make sure to check your spelling.
There's probably some event.
on_message won't trigger iirc, because no message I sent
Check the actual docs. The rtfm cmd can be outdated
how can i create a modal in pycord
hi, when my bot responds with a link, there is an embed that discord automatically generates, possible to turn it off?
Here's the modal dialogs example.
@cursive heron
Add <> around the link
worked, thanks!
How would I pass extra arguments to a View class that will display buttons? For learning purposes, I want to make a Poll command that takes in several options and displays a button for each.
Subclass and override the init method
So something like this?
def __init__(self, data, *args, **kwargs):
super().__init__(*args, **kwargs)
self.data = data```
I should probably go learn about Python subclassing and overriding... 😅 Sry. At least I know what direction to head now, thx.
Not wrong tbh
Yea OOP is very powerful
It is also necessary to properly use dpy
I love OOP, but I'm so used to it in other languages and Python is growing pains for me, haha
dpy?
ahh
💀
💀
true
I won't have to do anything special if I put this in a Cog, right? Just make the view a nested class and proceed as normal?
Ok, I keep hearing this, and I have to ask... What's the deal with Cogs? I was given the impression that Cogs should be used to organize your larger code projects by splitting up the code into different modules/files. Is there a better way to do this?
cog could be ambiguious: it could refer to the actual file, or the actual class in the file.
here, I'm referring to cog as the class
Ohhhh, so when you said to put it outside the cog, you meant the cog class within the cog file?
ohhhhhh
yes
Forgive my ignorance, but can you call a class while inside a different class?
yes
So, the View class is just, I guess, within the global space of the file?
yeah
Is this true with Java too?... I'm so used to only having one class per file with my Java projects that all this Python craziness is giving me a run for my money, lol
java literally only allows you to have one global class per file.
But you can have inner-classes in java, but not really standard practice
Ahh, okay, I'm not crazy then 😅 haha. Just need to get used to Python then. Thx!
yw
hmm
Hmmm
Hi guys, i have a code that get some options from a yml file and creates an option for a dropdown menu with them it works fine but i dont know how to make a callback for every option. The callback should change the channel name and it is also specified in the configuration file.
This is my yaml file
dropdown:
#You can create as many options as you want, Max is 25 (Discord Limitation)
option1:
name: "Account"
description: "For issues regarding your in-game account."
emoji: ":bust_in_silhouette:"
ticket_name: ":bust_in_silhouette:┃account-{interaction.user.name}"
option2:
name: "Store Support"
description: "For issues regarding the store and payments."
emoji: ":money_with_wings:"
ticket_name: ":money_with_wings:┃store-{interaction.user.name}"
This is how i get the values:
menu_options = [
discord.SelectOption(label=dropdown[option_key]['name'], description=dropdown[option_key]['description'],
emoji=dropdown[option_key]['emoji'])
for option_key in dropdown
]
And this is my dropdown:
@discord.ui.select(placeholder=ticketchannel['dropdown_placeholder'], min_values=1, max_values=1, options=menu_options,
custom_id=f"menu")
My code:
@bot.listen()
async def on_message(message):
ms = message.content.lower()
if "hello" in ms:
await message.reply("Hey!")
elif ".gg/" in ms:
await message.delete()
The above one works, that one with hello!
But the .gg doesn’t work, why?
.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 want to delete all msgs with .gg/ in it
Your current implementation will not work and you will need to subclass discord.ui.Select to get dynamic options.
if your message has "hello" and ".gg/" in its contents, it will only reply with "Hey!" and the message will not be deleted.
I know, the "Hey!" Shouldn’t get deleted. Only the ones with .gg/ in it
did you re-run the bot prior to testing
yes
is the indentation correct?
I'm assuming it's just discord formatting.
So it should work?
have you tried logging what the actual message content is?
No
I could try that
It isn't even printing
The content
elif ".gg/" in msg_cnt:
await message.delete()
print(msg_cnt)
Is the event firing or is the content None
put it outside of the conditions
wdym, sorry I ain’t a good English speaker :/
put the print statement outside of the if and elif statements
is there any way for me to detect if a channel or thread with a certain name already exists?
if else?
wdym? im pretty new to this
Do you know basic python?
yes
so?
there isnt any api stuff i need to call?
.rtfm channel
discord.DMChannel
discord.DMChannel.can_send
discord.DMChannel.created_at
discord.DMChannel.fetch_message
discord.DMChannel.get_partial_message
discord.DMChannel.history
discord.DMChannel.id
discord.DMChannel.jump_url
discord.DMChannel.me
discord.DMChannel.permissions_for
discord.DMChannel.pins
discord.DMChannel.recipient
discord.DMChannel.send
discord.DMChannel.trigger_typing
discord.DMChannel.type
discord.DMChannel.typing
discord.ChannelType
discord.ChannelType.text
discord.ChannelType.voice
discord.ChannelType.private
.rtfm thread
discord.Thread
discord.Thread.add_user
discord.Thread.applied_tags
discord.Thread.archive
discord.Thread.archive_timestamp
discord.Thread.archived
discord.Thread.auto_archive_duration
discord.Thread.can_send
discord.Thread.category
discord.Thread.category_id
discord.Thread.created_at
discord.Thread.delete
discord.Thread.delete_messages
discord.Thread.edit
discord.Thread.fetch_members
discord.Thread.fetch_message
discord.Thread.flags
discord.Thread.get_partial_message
discord.Thread.guild
discord.Thread.history
Thank you
gat a tuple of ids from a db but getting the category returns None
category = self.bot.get_channel(res[0])```
(1088104344806756442, 1088104170369863790, 1088104378549928036, 665380862568955935, 673602588972941323, 665384487357513741, 731520984170889236, 673619055961178132, 665380774941556759)
try fetching it
??
.rtfm fetch_channel
discord.ext.commands.Bot.fetch_channel
discord.ext.commands.AutoShardedBot.fetch_channel
discord.AutoShardedBot.fetch_channel
discord.ext.bridge.AutoShardedBot.fetch_channel
discord.AutoShardedClient.fetch_channel
discord.ext.bridge.Bot.fetch_channel
discord.Guild.fetch_channel
discord.Guild.fetch_channels
discord.Client.fetch_channel
discord.Bot.fetch_channel
fetch it
hmmmnever used fetch before
i mean only fetch it if the channel is None
whats the difference between get and fetch
get is cache
fetch is api call
ahh
Traceback (most recent call last):
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\philc\Desktop\Artemis-2.0\bot\src\cogs\medbayV2.py", line 161, in nffc_callback
nffcticket = await interaction.guild.create_text_channel(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1263, in create_text_channel
data = await self._create_channel(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1152, in _create_channel
parent_id = category.id if category else None
^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'id'
res = await get_ids(interaction.guild.name)
# get the first word of the guild name
# squadNames = platoon_search(platoonName)
print(res)
NFFC_category = interaction.guild.fetch_channel(res[0])
print(NFFC_category)
await it
something im about to become acquainted too
00:44 for me
how would i do subcommands (like /queue dungeons)?
thanks again
Hi there, I just started and I am following the Quickstart guide. Is there a way to find all of the guild_id's in Python?
what?
Do you know basic python?
Over here, there is the guild_ids argument for the decorator but how do I find all of the guild_ids that my bot currently has?
did you read?
if you want to make a global command, you just omit the guild_ids arg
@young bone Yes, I did read. From what I understand is that it is asking me to put a list of guild_ids where I want the command to work. But HOW do I find these guild_ids?
@silver moat I know but I want to know how to make it specific to certain guilds.
Hence, I want to find out HOW to find the guild_ids
right click at the server and copy the id
Yes I know that exists. Is there a way to do it in Python where I don't have to individually go to every server where the bot is in?
that would just be a global command
Maybe I phrased it wrongly. I don't want a global command.
I want to:
- Find the guild_ids for which the bot has (find out what server(s) the bot is in)
- Use the guild_ids argument so that I can only allow certain guilds to use the command
My problem is that I don't know how to do (1) via Python. I know that it can be done manually by copying the id in Discord.
but you know the basic´s of Python?
do you not want the bot to work in DMs or something?
Global commands work in every guild.
@young bone I'm still learning but I think I know the basics.
@silver moat I just want to limit the commands to certain guilds not all guilds.
for guild in bot,guilds:
guild.id # the guild ID
Thanks, looks good. May I know how to find out that guilds has the attribute id? When I clicked the Bot documentation, I found guilds but couldn't find any further information on it. https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.guilds
You are way faster than me xd
ah ok, so i was looking at the wrong place. thanks!
What are the arguments for raising CommandNotFound to get the command and context for the error handler to use? Might be confusing but I want to raise that error since something my error handler does for that error I need to use.
Is there any way to send voice messages using Discord bots? (Perhaps webhooks?)
it's not documented yet
Sad 
Any idea how long approximately Discord will do this?
Many tech companies have no ETAs, only due dates, and it is not public info
Oh, okay. Fair enough
message.author.color gives black
How to get banner color
message.author.accent_color gives none
Is it possible to change the color of a select menu or is there only the default gray color?
Okay too bad.
Do you have an idea how to make it visible that you have to select something? So that it is a mandatory information?
My original idea was to make the select menus red and when everything is filled in make them green but that doesn't work.
You could send a red image that points to the select.
Good idea I will test it as it looks 🙂
class buttons(discord.ui.View):
def __init__(self, bot):
self.bot = bot
super().__init__(
timeout=None
)
@discord.ui.button(label="Reject", custom_id='reject_button', style=discord.ButtonStyle.red)
@discord.ui.button(label="Accept", custom_id='accept_button', style=discord.ButtonStyle.green)
@discord.ui.button(label="Publish", custom_id='publish_button', style=discord.ButtonStyle.blurple)
async def button_callback(self, button, interaction):
if button.label == "Reject":
oldEmbed = interaction.message.embed # pull data from old embed
embed = discord.Embed(title="Question Rejected",
description=oldEmbed.description,
color=discord.Color.red(),
timestamp=datetime.datetime.utcnow()) # create new embed with old data + edits
embed.set_author(name=oldEmbed.author.name + oldEmbed.author.discriminator,
icon_url=oldEmbed.author.avatar) # i still have to include this
return await interaction.message.edit(embed=embed) # edits original message
else:
def check(m):
return m.author.id == interaction.user.id
uTimeRemaining = time.time()+120 # represents a unix time 2 minutes into the future
await interaction.response.send_message(f"What is your response to the question {interaction.user.mention}?"
f"Time remaining: <t:{uTimeRemaining}:R>")
test = await interaction.client.change_presence(activity=discord.Game('Test'), status=discord.Status.online)
message = await interaction.client.wait_for('message', check=check)
have this code to try and make a multi button message but it only adds one, what have i done wrong and how do i fix it?
checked examples but i didnt see anything that uses multiple buttons
now realizing this means i shouldnt actually be doing this style of stuff
oops
2 main ways
- have separate functions; each function should have a single button decorator, and you handle the logic for that specific button instead of all of them ```py
@button(label="Reject")
async def reject_button(self, button interaction):
...
@button(label="Accept")
async def accept_button(self, button interaction):
...2) Define more buttons inside `init` and assign the callbackspy
def init(self, bot):
reject = discord.ui.Button(...)
accept = discord.ui.Button(...)
reject.callback = self.callback
accept.callback = self.callback
super().init(reject, accept, ...)
async def callback(self, interaction):
...```
ok this is actually insanely helpful, tysm
or 3) create interaction_check inside your view which will act as a "callback" for the entire view
this isn't exactly intended and so some people recommend against it but it works...
allgood
though be cautious; a standard callback without the decorator doesn't have a button argument, only interaction. in this case you should either:
- use
interaction.custom_idto identify what was pressed - if you need the button object itself, use
self.get_item(custom_id)
gotcha
quick question on this second bit tho, what do i put in the super()._init_? i dont actually 100% know what goes there
your original placement was fine
i just did it like that as an example since you can initialize a view with items with that format instead of using add_item
icic
i am getting a separate issue though now
sorry if this is getting old i've never worked with buttons
very confusing
did you use button or Button
button is the decorator while Button is for usage as a regular item
nice
oops lol, tyty
giving you the credit in the script for this lol, this made my life way easier
haha you don't need to, ultimately we're always learning stuff from others
stackoverflow is so famous for a reason
both famous and infamous lol
-1
Hey, i got a quick question. Is it "bad" to use intents.all() even if we don't need all of them ?
In my case i use the none() then i enable the ones i need, but i see a lot of people enabling all of them even for basic bots, so i question myself xD
I would say it is bad practice. You should never ask for more than you need. There may be slight performance gains by not enabling all (Not 100% sure on that). Also if you enable message_content and do not need it it could lead to verification problems.
Overall all is mainly used by beginners and people who do not understand intents
Thanks for the answer !
But message content is needed for commands no ?
Prefix commands yes, slash commands no
👌
where is the "subclass button" way? 😭
that is the only correct way

I mean I guess you can but they were like 90% of the way there with the decorator
subclassing button is much better than doing button.callback = some_func ngl
Not really
Especially when you have 3 buttons which do the same thing
You can subclass but ultimately it's accomplishing the same thing without making too many jumps
cleaner to read imo 
heyhey
I get a message from a slash command, and in response I want to send a file and nothing else.
my current code is
await ctx.send(file=discord.File(f"showorder.txt"))
return
But right now it keeps saying "waiting for bot to respond" (which makes sense because I'm not doing a ctx.respond)
Is there a way to e.g. respond with an empty message, or let discord know I've sent a response but not to respond with a message?
not possible for a slash cmd. you could send an ephemeral message that says smth like "Sent!"
Yeah, makes sense. Just wanted to check. Thanks!
👍
can't you just ctx.respond with the file?
that counts as a response...
oh? it does? I wasn't sure if files were allowed in a respond instead of a send
That fixes it, ty!
all good, sending a file still counts as a message so it works
that's even better than what I wanted 
Unrelated to pycord where do you guys host you bots?
Raspberry Pi
It's more out of curiosity than necessity, as I could do this without type-checking - but still:
Any idea why query: str | int lead to the error? I'm on Python 3.11.2 and Pycord 2.4.0
discord.errors.ExtensionFailed: Extension 'cogs.dbadmin' raised an error: TypeError: Invalid usage of typing.Union
Edit: Ah, It's because Slash commands don't accept this type, gotcha
#1047345278631559279 message
I don't have one 💀
Linux server, using it for hosting others things on it too, and a discord bot is rather small
@solemn idolBut where which website?
Hi ! Is there a way to create ForumTag in a ForumChannel ?
We have access to get_tag() and all the available tags but i don't see a method to create one as we have to create textchannel, thread etc...
Also, in the docs there's not hypertext link to ForumTag, idk if it's known
its my own linux server... you have to find a hosting yourself... and I am not necessarily hosting websites on it
so it's kind of weird, but it's in ForumChannel.edit under available_tags
https://docs.pycord.dev/en/master/api/models.html#discord.ForumChannel.edit
this takes a list of discord.ForumTag objects, however it seems they were forgotten in the docs. That being said, here's the main documentation for it py class ForumTag(Hashable): """Represents a forum tag that can be added to a thread inside a :class:`ForumChannel` Attributes ---------- id: :class:`int` The tag ID. Note that if the object was created manually then this will be ``0``. name: :class:`str` The name of the tag. Can only be up to 20 characters. moderated: :class:`bool` Whether this tag can only be added or removed by a moderator with the :attr:`~Permissions.manage_threads` permission. emoji: :class:`PartialEmoji` The emoji that is used to represent this tag. Note that if the emoji is a custom emoji, it will *not* have name information. """
(it's designed this way because that's how it's done on the API)
Yeah i saw that, but how do i create a forum tag ?
I thought of the solution create tag + append to available tags but i need to create one before, and i can't generate ids etc...
that is how you make them
It's not an issue if its created manually ?
Like the id is going to be 0
it'll get a proper ID when it's sent to discord
that being said it would be more convenient if we created our own methods to make this easier
yup
Can we pass custom members to an user select?
Yes
how? 😭 the docs aint doc'ing
no
ok, makes more sense ty
And if you would use a normal select menu?
Yeah, I will. User selects were prettier
Aren't those what code spaces do?
no, that's intended to be used a dev environment
fair enough
and I don't think I only want my app to be running for 60 hours a month
true
I'm trying to get my bot to join the vc but it wont
@commands.command()
async def connect(self, ctx):
if not ctx.author.voice:
await ctx.send("You are not connected to a voice channel.")
return
channel = ctx.message.author.voice.channel
await channel.connect()```
What is the py-cord Version?
py-cord==2.0.0rc1
#library-updates 2.4.1
Bruh, i should really keep up with updates lol
Yes
I've just updated and still no luck
Does it error or sum?
nope
yeah, I add print(channel.id) right before the await channel.connect() and it gets the channel Id
Do you have intents?
intents = discord.Intents.all()
client = commands.Bot(command_prefix='!', intents=intents)```
Anything else installed?
What do you mean?
Why should it change?
idk, just didnt know if i needed to put self. in front of it
Does the bot has the permission to join a vc?
can a bot get webhook links'
like can i get all the webhooks in a channel and then use a random one to send a message
cuz i keep getting https://discord.com/api/webhooks/[webhook id goes here]/None
nvm i fixed
I added a try except and got this error: PyNaCl library needed in order to use voice
Install it with pip
This happens when I do: bot.dispatch('command_error', context=ctx, exception=commands.CommandNotFound)
I want to dispatch a command error since my command handler handles something important.
.rtfm discord.ext.commands.on_command_error
Target not found, try again and make sure to check your spelling.
.rtfm discord.ext.on_command_error
Target not found, try again and make sure to check your spelling.
.rtfm discord.ext.commands.Bot.on_command_error
Says exception is a valid argument
they aren't kwargs
they're positional
Oh
(pretty sure all events only use positional args)
Can you elaborate?
Are you trying to do like, random 1 of the 4 buttons is the right one?
Its supposed to be like the placement of the 4 buttons under the message be randomized
Ah
1 way would be to add buttons using view.add_item instead of the decorator
Oh wait there is a better way
But will it be randomized everytime ? or do i put it in a list and use random ?
Try using random.shuffle on self.children
The latter
I have just got into bot development and im a beginner can u please explain it in a simpler form?
Im trying to use this
ah it aint workin
its same sequence everytime
So uh
self.children returns a list of items in the view
You can try and shuffle these items in the init
Smth like
class MyView(discord.ui.View):
def __init__(self, ...):
super().__init__(...)
random.shuffle(self.children)
...
I'm not sure if this would work
So try it and see
k i'll try and let u know
Thanks it worked well
i had another query
can i ask if u dont mind ?
Nice
Sure
Ok so i want to fetch for the button if its the correct one pressed and display "You choose the correct one"
in this case
And random fruit is defined in slash command
It generates a random fruit name everytime as expected
So you want to do some action if the clicked button is correct?
If yes then you should subclass Button
can u explain how ?
how can i replace a file when editing a message?
Why do I always get this error when I want to edit my interaction?
await message.edit_original_response('This is a Test', view=await View(self.bot, data, False))```
Error:
Interaction.edit_original_response() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given```
content is a kwarg
content="..."
Thanks! 🙂
i would do smth like
class MyButton(discord.ui.Button):
async def callback(...):
if self.label == self.view.correct_label:
...
class MyView(discord.ui.View):
def __init__(...):
super().__init__(...)
label_list = [...]
random.shuffle(label_list)
for label in label_list:
self.add_item(MyButton(label=label))
@knotty brook ^
use the attachments kwarg instead of files kwarg
k thanks
i'll try
Can i have a fix for this ?
return await ctx.respond(embed = wrong)
^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'respond'```
yes i have given ctx as and attribute
You can't send a message or a response to an Interaction as you send it in a slash command.
In a slash command we use ctx as discord.ApplicationContext
Here you want to use interaction.response.edit(...) or interaction.original_response()
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 ...
Interaction.response.send_message
Ye i used interaction.respoce.edit_message as i dont want the bot to send another message
OR maybe wait i need to send_message
cuz buttons
How do i disable the buttons after certain period ?
If you don't mind disabling all the children after a period you can give a timeout to your view
like timeout arg while calling it ?
or like this
it isnt working for some reason
i can still click the buttons
It's on_timeout and it's a method
The disable_on_timeout is set to False by default
mhm i need to set it
so u mean this ?
ye but im used to calling Functions and not Method
how can i remove a file when editing a message? file = None just throws an error
pass timeout and disable_on_timeout kwargs to the super init
pass [] to attachments kwarg
Thanks, How can i get rid of buttons associated to a message sent by a bot ?
On interaction with the buttons ofc
edit the message and pass view = None
await interaction.response.edit_message() ?
.tias
depends on when and where you are doing it
Can i assign an async function on interaction to a button?
??
if you havent used the library before, i suggest checking out the guide
.guide
works, thanks
how can i get a user's description? i dont see it in the docs
Where did you search it at the docs?
Member then looking thru attributes? I didnt see anything matching
theres status and activities and everything but no description
I think the api doesn't provide the user's bio
cmd = bot.get_command(cmdName)
print(f"{prefix or slash here} {cmd.name}: {cmd.description}
How to get command is prefix or slash command
Are you using bridge?
How can I do sub options like /command option1 option1sub but not have option1sub appear on option2
What's that
Show me your bot = line
You will have to use auto complete
Here's the slash autocomplete example.
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all(),help_command=MyHelp(),activity=discord.Activity(type=discord.ActivityType.listening,name='!help'))
All you commands will be prefix.
what?
i have slash command too
Wait nvm, I forgot slash were backwards compatible.
you can use
isinstance(cmd, discord.SlashCommand)
hmk thx
Backwards compatible isn't exactly the right phrase considering the structure of the clients we have
Are messages automatically evicted from the cached_messages once they're deleted?
Why
bot.get_command(command)
Gives none
But commands that are in main.py works
yes
did you get the name right
Nope commands in cogs gives None
Wiat
async def Help_command(self,command):
cmd = self.bot.get_command(command)
print(cmd)
if isinstance(cmd,discord.SlashCommand):
prefix = "/"
else:
prefix = self.bot.command_prefix
embed = discord.Embed(title=f"Viewing {cmd} command", description=f"{prefix}{cmd} : {cmd.description}")
embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar)```
output:
None
None
chat
slash commands use get_application_command
also if it's a slash command, you can use command.mention to have a mention-style output of the command
like </example:1009144375709814896>
I'm using it in a custom help command
yes that's why im suggesting it
Myhelp
you might find it looks better in the embed
Ohk
and then users can easily click it to use the command
Is there a way to disable that? some event I could overwrite?
cmd = bot.get_application_command(name="link")
print(cmd)
still gives None
not conventionally since it's in a raw state event, but you could just catch the message yourself in an on_message_delete?
async def Help_cog(self,cog):
cogs = self.bot.get_cog(cog)
embed = discord.Embed(title=f"Viewing {cogs.__cog_name__} Category" , description=cogs.description)
command_list = []
for cmd in cogs.get_commands():
if isinstance(cmd,discord.SlashCommand):
prefix = "/"
else:
prefix = self.bot.command_prefix
command_list.append(f"`{prefix}`**{cmd}**: {cmd.description}")
embed.add_field(name="Commands",value=f"".join([f"{x}\n" for x in command_list]))
embed.set_author(name=self.bot.user.name,icon_url=self.bot.user.avatar)
return embed
commands are showing when i call them from cog
sup, how to fetch other defered interaction from others bots like a bump?
.rtfm message.interaction
oh i got it
Hello, so i want my bot to delete invites. The first one works (hello) but the second doesn't.
@bot.listen()
async def on_message(message):
msg_cnt = message.content.lower()
if "@lucid tinsel" in msg_cnt:
await message.reply("hello!")
elif ".gg/" in msg_cnt:
await message.delete()
print(msg_cnt)
the .gg/ doesnt delete the messages
(the bot doesnt lol)
do you have message intents?
and what are the permissions?
administrator
but if i ping the bot, it responds. but the elif doesnt work somehow
oh, sorry. it was discord messing around
it's all fine
discord.ext
Just double checking, i can't make it so you can select more then 1 role per parameter in a slash command, correct?
you mean if you use discord.Role?
Yeah
Im not really sure if this is possible
Yeah i didn't think so either
Not as a role option. But you can accept it as a string of role mentions
You would need to parse it in your code
A better wya would be to send a role select menu
True
Why can't I make my Paginator (the buttons of it) persistent like this?
What is the right way to do it?
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(await PaginatorInfoView(self.bot))
self.persistent_views_added = True
class PaginatorInfoView(Paginator):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
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=custom_buttons, custom_view=view, timeout=None, author_check=False)```
My try except block isnt working. its in a Cogs.listener on_guild_join. I try to read the audit logs, but if i cant, i want it do something. But when it fails, it just logs the error in the terminal like normal "Ignoring exception...". Any ideas how to activate the except block?
i see that errors in events go to on_error handler. any way to override this on a case-by-case basis?
nevermind^
any quick way to see who invited the bot to a server in on_guild_join?
you can check the audit log
Another way? Problem is security bots blocking my bot from viewing audit log, even when the inviter grants my bot View Audit Logs permission initially
then there is no solution
unless you want to use OAuth2 and store the user somewhere...
which I don't recommend unless this is a very important feature of your bot
Bet thanks
I should note this down
I have a class that extends discord.Bot and has ivars that I need to access upon interaction with a button, but with the button being its own class, I'm not sure how to do this. Any ideas?
interaction.client gives you the bot object iirc
how do I resolve a button callback?
defer with invisible=True
...i think, if it doesn't work then idk use interaction.response.edit_message
Just do a simple defer
interaction.response.defer()
That is a valid response for buttons
hey, how do I send a mention along with a embed? like together in one single message?
You would need to send the mention in the message content (not the embed)
So smth like await ctx.send("@silent meadow" , embed = embed)
okay lemme tias
I get this error:
discord.errors.ExtensionFailed: Extension 'cogs.commands.Test' raised an error: TypeError: button() got an unexpected keyword argument 'url'
and this is my code:
@discord.ui.button(style=discord.ButtonStyle.link, url="https://example.org", label="Test")
my IDE and the error says that the url argument is an unexpected argument, but the docs say that there is an argument called url
you cant add url buttons using thee decorator
because url buttons cant have callbacks
you need to add them using view.add_item
Here's the link example.
ok thanks
np
maybe the interaction took to long to respond
Or it doesent exists anymore
Hey, I was running a bot using pycord for some times and it seems like for a period of time, guild_ids were kinda... broken. Where it was supposed to end with 360, the bot was reading 300. And now, he's reading it correctly again but the problem is that my db is now kinda broken.
What causes that?
Yea you are taking too long to respond. Defer at the start of the code and then send followup
What?Can you be a little more detailed?
Do this
async def callback(...):
await interaction.response.defer()
# ... rest of your code
await interaction.followup.send("Hi")
Ok thanks 😁
Ok/Now I have one new problem
wrong method, should be interaction.edit_original_response in this instance
Ouuu ok
hey, just wondering, is it possible to create subgroups in bridge commands? couldn't figure out how to do that
yes
.rtfm _subgroup
1st
ye, i could do that for the slash variant, but it's not going to work the same way in the ext variant?
thanks anyways
bridge was made so that it would work the same with slash and prefix
say i wanna have command structure such as this:
group1
-subcmd1
-subgroup1
-subcmd2
is it possible to have this structure both in slash and ext? the methods you linked me are from the slash variant. do i understand correctly that if i'll make a subgroup here, it won't be reflected in the ext variant? (i won't be able to type say !group1 subgroup1 subcmd2)
or am i being crazy and if i'll add a subgroup in the BridgeSlashGroup it's actually going to work in the message command magically?
sorry if im being stupid or smth
oh my bad
there is decorator for the groups
i forgot bout that
stupid me 💀
The reference manual that follows details the API of Pycord’s bridge command extension module. Bots: Bot: Methods def add_bridge_command,@ bridge_command,@ bridge_group. AutoShardedBot: Commands: B...
also see if the github example has it
Here's the bridge commands example.
it's ok
but how to use that decorator to actually make subgroups? i figured how to make regular groups, but still no idea how to implement a structure i provided above
i think its kinda impossible. i looked through ext.commands and there's just nothing on subgroups.
but thanks for your help still, and have a good sleep XD
it should be a relatively simple pr imo
yup. thinking about that
lol would be cool
What's this?
Ohhh
Curious how to allow multiple selections from slash command options
you kinda can if you use autocomplete
definitely clucky tho
ahh, good idea! It's for "backend" use so that should actually work! Thanks!
class HelpView(discord.ui.View):
def __init__(self,bot,*args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.bot = bot
self.helpembed = HelpEmbed(bot)
options = [discord.SelectOption(label=info['cog'], description=info['cmds'][:99]) for info in self.helpembed.Help_list()]
self.select = (discord.ui.Select(placeholder="Select a option", min_values=1, max_values=1, options=options))
self.add_item(self.select)
self.select.callback = self.on_select
async def on_select(self, interaction: discord.Interaction):
select = self.select
cog = select.values[0]
if cog == "Main Manu":
embed = await self.helpembed.HelpMain()
else:
embed = await self.helpembed.Help_cog(cog)
await interaction.response.edit_message(embed=embed)
how to show selected option in place holder
Whenever someone creates a forum thread in a specific forum, how do I check who created it?
hello I always get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message when I do channel.fetch_message(id) from a very old message
why isnt the bot able to ping the role?
I have checked the follwing things: I have the role, The channel perms are correct, The bot has an admin role ✅
@discord.slash_command(name ='test1', description="this is a test command :D")
async def test(self, ctx):
embed = discord.Embed(title = "Friendly Reminder!", description = "Please do bump this server by using the command : `/bump`")
await ctx.respond("<@&1083433733857755269>", embed=embed)
(please ping for reply)
How can i can be staff
You are new at Discord and at the server
Try using allowed mentions
You could make your own server. XD
Hi, in my button callback from a button (the message has two buttons) I want to access the other button and change the label. this is how I do it:
for row in components:
if isinstance(row, ActionRow):
for button in row.children:
if button.custom_id == "no_button":
current_label = button.label
match = re.search(r'\d+', current_label)
number2 = int(match.group())
print("nummer 3: " + str(number2))
button.label = f"No ({str(number2 - 1)})"
print("nummer 4: " + str(number2 - 1))
``` the problem is that my IDE says this in the line `if button.custom_id == "no_button`: `Unresolved attribute reference 'custom_id' for class 'Component'`
and this: `'Component' object attribute 'label' is read-only, 'Component' object has no attribute 'label' ` in this line: `button.label = f"No ({str(number2 - 1)})`
how can I solve this?
View.children returns a list with the buttons or whatever you have in your view
Just index it and change the label
ok, I will try it
you cannot ping roles in a respond
xd
you shouldn't edit message.components directly; either:
- use
ui.View.from_message(message)to get a new view and edit the items there - if you know the custom_id for the other button, use
self.get_item(custom_id)(assuming this is in your view class?) to access the button object and edit it
you lose out item callbacks when using View.from_message
Which is why I suggested the latter
how do i edit a button label while using a class view like the docs?
hey im looking for a suggestion, how can i make a modal dialog have like a boolean value for the question ( i wanted to integrate a select menu inside a modal but found that, that it is not supported) for example if the question is something like "Are you homeless?" and i want the users to have like two options to choose from "yes" or "no" , if you can give me any suggestion how can i make this as user friendly as possible i would appreciate it
Discord is not really supporting a Menu inside of the modal
yea, can you give me a suggestion of a way i can do it tho 😄
i think asking the question and having the user input the value is too problematic
when it's a yes or no question
no no, i do understand that discord does not support the menus in modals, but i am asking if you have somewhat of an idea
of implementing that
No, sorry
alright tnx for the reply tho gn
but what you could do is sending the menu after the user close the modal
Hi, does anyone know how to add descriptions to the arguments of slash commands? I mean not the description of the command itself, but rather the description of the argument.
from discord.commands import Option
Option(str, description="")
Is there a clever way to sanitize a user string input that will eventually be used with Embed.set_image(url=str)? I noticed inputing something simple like "test" will crash the Embed routine.
it has to be an image
I understand that. My question was if there was a clever way to sanitize a string input to satisfy this requirement.
My leading idea is a regular expression, but I wasn't sure if there was an easier object based approach or something...
not really, the best you can do is check it's a url at all
image urls come in many formats, discord itself doesn't validate anything
