#Basic Pycord Help
1 messages · Page 12 of 1
hello, quick question:
user= discord.utils.get(ctx.guild.user, id = user_id)
is what I try to use in order to fetch a certain user but:
AttributeError: 'Guild' object has no attribute 'user'
do you guys have the right way to do this pls
it's stable enoguh to use for a production bot right
but that one for some reason results in modulenotfound
ig i'll wait
Yes
.rtfm guild.get_member
ty
ig i'll just wait for the actual release
Huh?
Did you uninstall py-cord
Show pip list
It won't happen anytime soon
i did
Show pip list
Uninstall discordutils
i uh need that
For what exactly?
just copy their code
what "code"
Is it possible to block a user from using your bot with on_application_command?
you could make an if else statement, so if the user is for example @mommy#6666 it would just return an error for the user that they are not allowed to use that command.
Yeah I tried that but the command still goes through
oh
ok
i did that, it's still not found
still modulenotfound
if ctx.author in blocked_user_list:
await ctx.respond('Nope')
return```
or just defer
Yeah i tried that but the command still executes anyway
What do you even have in the list?
My user ID.
may i see da code?
@commands.Cog.listener("on_application_command")
async def on_application_command(self, context: discord.ApplicationContext):
print(context.command.name)
if context.user.id in blacklist:
await context.respond("Nope")
return
that should go into the command
that event only gets triggered after/when a command is executed
Yeah the reason I wanted to see if it was possible in an event is because I have a lot of commands and I didnt want to add a check to each one
well maybe there's a way i dont know of but eh 🤷 that's what i'd do
Override on_interaction instead
Or create a decorator for your commands
Yeah im just going to use commands.check
for that you could use a error handler
Hello, I'm trying to send a paginator with a slash command using paginator.send(), ctx is discord.ApplicationContext but im getting:
Traceback (most recent call last):
File "/root/Testinator/testinator/lib/python3.11/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/root/Testinator/testinator/lib/python3.11/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/root/Testinator/testinator/lib/python3.11/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>
you use paginator.respond(ctx.interaction) for interactions
Yes I'm aware of this but is there a way where i can send the paginator instead of it being a response?
Hello. Slash commands are not displayed in Cog. What could be the problem?
Are you loading the cog?
Presumably.. yes. How can I check this?
Are you using bot.load_extension
Yes
Do other cogs work?..
This is the only Cog in the program
Where intents
I learned more about the problem. It was Slash commands that stopped showing up
Everything was fine on the test bot with the same code, what happened to this?
guild permissions?
Oh.. it turned out to be true. Thank you
so i havnt used pycord in while i have message being sent via chanel no interactio connected to it wuth button i want button to edit the message sent to channel i tried ```async def green(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.edit_original_response```
but it just receives 404 error and it said edit original_message was depreceated which is what i thought i used before
I am not sure but could it be that the message it tried to edit is too old?
just like that bots cant delete messages which are too old
its instant
like within second or two
i cant even read the title
oh do i need intents? evn though bot sent message
Use interaction.response.edit_message
that worked for editing thanks
i also need to get content of message and original_response still is 404
turns out its interaction.message not original_response
original_response is when you send a interaction.response.send_message
does pycord / discord api allow access to the pronouns of a user?
or is that under the same clause as user bio?
no and yes
What would be the easiest way to check if a user is in a specific Discord Server? All the methods I've seen aren't working properly. I have a task running every 10 minutes, and I want it to check if specific people are in a premium SQL database/also in the Discord Server.
I've used:
guild = self.bot.get_guild()
And checked
guild.members
My issue is the Discord cache seems to reset randomly? Causing it to sort of flush and automatically trigger my system the wrong way.
Is there a straight way to simply check if a user is in the Discord or not without using any sort of cache? So the result is always correct?
Well if cache is empty just use fetch instead of get
Don't have the specific stuff for it but that's what I'd look for
But look this is my issue
This is the code
The channel1 id is still returning None. I tried get_channel, fetch_channel doesn't work.
I'd just do py channel1 = self.bot.get_guild(id) or self.bot.fetch_guild(id)
One of those could be async/awaited
No channel1 is suppose to be the channel ID so I can send a message to that channel
Just gotta 
Well yes, but you can only send to it if you retrieve the channel obj IG
get_channel, fetch_channel, discord.utils.get(guild.channels, id=).. the docs are giving me these options.
None of them work.
Is it possible to use fetch channel since I'm fetching the guild?
fetch_channel returns a courtine
chan1 = bot.get_channel(settings.statuschannel_id) or await bot.fetch_channel(settings.statuschannel_id)``` snippet from my bot
fetch_channel returns this error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/tasks/__init__.py", line 176, in _loop
await self.coro(*args, **kwargs)
File "/home/container/Cogs/premium.py", line 34, in scan_task
await channel1.send("Ok")
TypeError: can't send non-None value to a just-started coroutine```
Did you await?
you don’t need to await
I didn't await. It's still raising the error.
If you don't need to. Why would it raise this error?
you do need to await
i think
idk how to use python
wuts wrong with my code?
print(hello world)
@hallow copper
hm?
Is it possible to manually scan and see which people are in specific roles, instead of relying on cache?
idkkk i haven’t actually worked on my bot in a while
ask chatgpt or sum
or read the docs or sum
ik but old answers are better that nothing
plus i wanna sleep
have you tried googling it?
Is there a way to get the list of all message/user commands?
logger.info(f"[cyan]Loaded {len(bot.cogs)} cogs[/]")
logger.info(f"[cyan]Loaded {len(bot.commands)} commands[/]")
logger.info(f"[cyan]Loaded {len(bot.application_commands)} application commands[/]",)
basically the last log isn't outputting what I expected :[
Feed bingAI the link to the docs and ask it
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 ...
I wouldn't really recommend it over cache though, what intents do you have?
Fetch has to be awaited
What is it outputting? Should be fine
I think it's 0, I can't exactly remember
I know all_commands was 1 which was incorrect for me as it should be 3
What if you do _application_commands?
I guess I'll have to mess with it when I can
What is menus supposed to be?
.rtfm ui.Select
discord.ui.select
discord.ui.Select
discord.ui.Select.add_option
discord.ui.Select.append_option
discord.ui.Select.callback
discord.ui.Select.channel_types
discord.ui.Select.custom_id
discord.ui.Select.disabled
discord.ui.Select.from_component
discord.ui.Select.is_dispatchable
discord.ui.Select.is_persistent
discord.ui.Select.max_values
discord.ui.Select.min_values
discord.ui.Select.options
discord.ui.Select.placeholder
discord.ui.Select.refresh_component
discord.ui.Select.refresh_state
discord.ui.Select.row
discord.ui.Select.to_component_dict
discord.ui.Select.type

Hey
@client.slash_command(guild_ids=servers, name="pillow_test")
async def pillow_test(ctx, member: discord.Member):
if member is None:
member = ctx.author
img = Image.open("img/welcome.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("fonts/Hanson-Bold.ttf", 40)
# Get image dimensions
img_width, img_height = img.size
# Get text size
text = f"Willkommen {member.name}!"
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
# Calculate coordinates to center the text
x = (img_width - text_width) / 2
y = (img_height - text_height) / 2
# Write Text on Image
draw.text((x, y), text, (255, 255, 255), font=font, stroke_width=1, stroke_fill=(0, 234, 255))
# Save Image
img.save("welcome.png")
# Send Welcome Image
await ctx.respond(file=discord.File("welcome.png"))```
how can i make the text to gradient?
for example red and black or something
how do i create quick empty interaction answer without sending a message? (to avoid interaction failed message)
You cant
Use an ephemeral message
Hey, so i have this basic command ```import discord
from discord.ext import commands
intents = discord.Intents.all()
client = commands.Bot(command_prefix="ku!", case_insensitive=True, intents=intents)
@client.event
async def on_ready():
print("Kuze has started")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Prefix: ku!"))
@client.command
@commands.is_owner()
async def hirek(ctx, msg):
channel = client.get_channel(1159774208642007040)
await channel.send(msg)
await ctx.send("The message has been sent to the specific channel")
@client.command
async def otlet(msg, desc):
embed=discord.Embed(title="Új ötlet érkezett!")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1139444058985599026/1159926636364439662/Frame_1.png?ex=6532ccdc&is=652057dc&hm=40b87264487bf7c2793d1f07222b6560fcc9e3250fd6a3ecaf42a7ebf271d193&")
embed.add_field(name=f"{msg}", value=f"{desc}", inline=False)
embed.set_footer(text="Köszike hogy segíted a szerver fejlődését")
channel = client.get_channel(1159774260374552619)
await channel.send(embed=embed)
and if i start the bot it starts and everything. But when i type ku!help it only shows the help cmd and if i type ku!otlet no error justcommand not found```
where is the () at the commands?
@client.command()
also
?tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
Still 0
Does the bot have to be ready when this is checked or something?
Oh, yeah. I moved the logging to on_ready() and now it properly shows 4
How does one disable pycord's logging...?
How did you get your logs to show up like this?
I'm using RichHandler from the rich package
def setup_logging() -> None:
"""Set up logging for the bot."""
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
datefmt="[%X]",
handlers=[
RichHandler(markup=True, rich_tracebacks=True),
],
force=True,
)
but yeah for whatever reason pycord's log messages are showing and I really don't want them tbh
This doesn't trigger at all. When a role is added/removed, nothing happens.
What are your intents?
hey so i have this code @client.command() @commands.has_role('-₊˚ | Partner intéző') async def partnerek(ctx, member, partnerszerv, szoveg): partnerek = client.get_channel(1159774325944111125) psz = client.get_channel(1159774283036360714) role = ctx.guild.get_role(1159773692486754304) await client.add_roles(member, role) await ctx.send("Siker") and i got this error:```Ignoring exception in command partnerek:
Traceback (most recent call last):
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\malna\OneDrive\Desktop\Kuze\main.py", line 40, in partnerek
await client.add_roles(member, role)
^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_roles'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\malna\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'add_roles'```
Try reading the error traceback because it tells you what you did wrong;
AttributeError: 'Bot' object has no attribute 'add_roles'
thanks, but i want the solution.
Is it possible to add a field with no name to an embed? I don't just want it to be an empty string, as this adds an empty line to the embed, the field name shouldn't exists or not use up any space in the embed
await member.add_roles(role)
Those are 2 fields, first with the name Feedback Threads, second with an empty string as the name, resultig in the weird blank line
its the same error
please someone can help?
The Bot object (in your case named client) doesn't have an add_roles method. You have to call the method on the member, as ramo told you to.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'add_roles'
You will have to fetch the member, you can't just pass a string and expect it to work
?tag learnpython
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
Unfortunetly no, You could use inline to make it look a bit better but it might look worse in your case.
Is there a way to have 2 embed fields inline=True and displayed next to each other accross the entire embed, without setting every third field to inline=False?
Dont think so
so many more places you coulda went to find it
nvm I am dumb
Wait nvm im dumb
It's basically discord.Member.add_roles whereas discord.Member represents your member.
You indeed have to first fetch your member and then add the roles to them.
@wise parcel
Can someone help me?
depends on the issue
Don't ask to ask please.
do you want the member id of whoever renamed a channel?
do you want a members online counter? or just for specific users?
just for specific users

and then check if its user XYZ and update the channel
Thank you
yo anyone got SQL server recommendations? wanna move away from SQLite
I use a NoSQL one xd
hmmm
I really like it to use MongoDB
postgres is fine
I second Postgres with asyncpg as the driver.
lets say after some event i want to wait 2 min before doing something, what is the best way of doing this? just asyncio sleep?
ye
time.sleep would block the entire bot for 2 minutes
you can try it out and see what will happend it you use time.sleep xd
Do you also use something like requests? @floral ice
httpx async
that is fine
Is there a way to limit what channels or users show up in channel or user selects?
You sadly cant. You'd have to use a normal select menu and filter it by yourself
Would the UI be about the same?
or is it just text if I opt for select
Channel and user selects return an object
Normal selects are string selects
So internally you'd have to get the user
:/ that sucks
So, what do I do about a user picking an option I consider to be invalid?
Is there a way to reject a selection?
How would it be invalid?
For example, I don't want people to be able to send messages through the bot into channels they shouldn't be able to
I have announcement channels and stuff and a command to move conversations between channels
I'm assuming you're using channel selects then
yes
'cause I want to use channel/user selects but I would need to be able to disallow people from selecting certain IDs
I mean like... say a person picks #announcements as a channel... how would I be able to "reject" that input?
I was hoping there'd be a way to customize the red error text that appears under selections sometimes
What
The interaction failed message?
Why don't you just respond to the interaction with a message
"You are not allowed to select this channel"
yeah
guess I'll have to edit the message and disable the buttons
'cause I have to send a message to get the view in the first place lol
and you're only allowed one message
Is there a way to convert a User to a Member? I'm kinda amazed that Message.author doesn't return a Member for me o_O
.rtfm guild.get_member
I eventually figured it out... Turns out I was missing an intent O_o
but um... now I have a new problem
How does one disable a button using the @ui.button decorator?
Why does discord.ActivityType.custom not actually display anything? How do I set a completely custom status without "Playing", "Streaming", "Watching", or "Listening"?
Probably using something similar to a select menus: select.disabled =True
Afaik just not working at all
I do it like this and it works fine:
await self.bot.change_presence(
activity=discord.Activity(
type=discord.ActivityType.custom,
name="Custom Status",
state=f"big balls",
)
)
Huh interesting
Is it possible to have dynamic options in a @discord.ui.select decorator that's within an overloaded discord.ui.View that accepts options as an extra input value?
Example:
class CustomView(discord.ui.View):
def __init__(self, options: list):
super().__init__()
self.options = options
@discord.ui.select(
placeholder = "Demo",
min_values = 1,
max_values = 1,
options = self.options # issue is here, obviously
)
async def select_callback(self, select, interaction):
# do stuff
the callback needs placeholder options basically
and then just do in the init self.funcname.options = options
Ahh, okay, thank you. That's what I was thinking, but I'm having a brain fart on the specifics of how to do this. Do you mind giving a code snippet example?
too lazy to filter out unnecessary parts
unclean code that is in dire need of rewriting but
it works
do not comment on my var names
What line should I look at? (what does it start with?) I'm a little lost
same
select needs an actual placeholder option inside the decorator
then just use self.funcname.options = whateveryouroptionvariscalled in the __init__
it took me a week of frustration to work that out, was a good way to learn OOP basics 😅
I need somewhere to store a large amount of data in dict format. Can I use Json for this?
Is it normal for the bot to be disconnecting this often? My my bot seems to just die after 10 minutes and go offline with no error. The bot doesn't even do much other than listen to on_message.
Is it possible to have a button without a label?
hi, how to set custom rich presence (RPC) with images and buttons?
can autocomplete have defer?
cuz i have lots of data
and it needs sometime to generate
using pycord?
you dont need to defer the autocomplete and it also doesn't have it
but it will always shows error messages
what is the error?
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
cuz it wait too long
i have already defered it
when the auto complete waited too long, it will shows the error
You should use a cache so you do not have to generate that many items every time. Also I think you need to rethink how your autocomplete works. There is no reason to generate a time stamp for ever minute for the next 100 days. You should wait until the user starts typing and then generate based off of the day or something. Then filter down the times. Autocomplete is not especially helpful if it just lists ever possible option when there are so many options. Another thing you could do is only suggest common times like XX:00 XX:30 XX:15 XX:45 and if the user needs to be more specific they can type it themselves.
Take a look at the picture attached please.
I wanted a slash command to display "Tratos" but always got "tratos56..".
So far i tried ctx.user.name & .display_name
same with .member.name + .display_name
member.nick returns None.
using the 2.5something - almost stable but not exactly - pycord version
Edit: Please ping me or use the reply function when you answer
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
@grizzled loom You would want member.global_name or member.display_name
I see you already tried display_name not sure why that does not work
I'll try that, didn't come across global_name while browsing the docs. must've missed it.
edit: display_name did work, but gave the version with a number.
thank you
but how should i let the bot wait until the user starts typing and generate
just wait until autocomplete is called and use the text already inputed
you should also check if its None or not or you will get a error soon
yes
you want to set bot's rpc?
yes
i only know how to add "invite button" to bot's profile
For what is rpc?
but i know how to add buttons to user's profile
rich presence
quick question how to write unittests for discord bot?
how can i invoke a command like a user
We have this branch but i dont think it is stable nor updated in a long while https://github.com/Pycord-Development/pycord/tree/unittest
how can i use @is_user() or @has_role on slash commands?
@commands.has_role('Role name') iirc
I am an Idiot at times.
Your advise was solid, my attemp too. the test bot was using an outdated pycord version. Big surprise it didn'd work as expected.
Hello!
Why does ctx.author.nick return None?
nvm
user doesn't have display_name on my server
why ._.
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
wth
You need to be on master or the temp dev release in #library-updates
2.4.X does not have that feature yet.
hello, does pycord support discord monetization? SKUs and entitlements?
nope
ty
does it work on slash commands?
ok
Is there any way to use a decorator like has_any_role in a button class to check if the user who clicks the button has the appropriate role or do I have to check this manually once in the button?
class CloseButton(discord.ui.Button):
def __init__(self):
super().__init__(
label="Close",
custom_id="close",
style=discord.ButtonStyle.red,
emoji="🔒",
)
async def callback(self, interaction: discord.Interaction):
does anyone have tips to make localization easier?
what is the problem with it?
Maybe just my format and way of doing it but its a tedious thing at times to just have to enter the file name, func names and then the var names as seperate entries in my json, and keeping track and organizing that can be quite annoying
Was just wondering if anyone with more experience got tips for some QOL
how do button role work after bot restart or something?
so there are two requirements for that timeout=None and custom_id
you have to use a view class
and add the view for listening
how does it work internally?
Here's the persistent example.
will bot looks whether it has any view with that custom id
i couldnt understand how that is working internally
it it possible to use Google Speech To Text and Pycord's voice to output realtime transcriptions into a discord text channel?
i know how to do it
dont use something like ```py
view = discord.ui.View()
so each view is given
- timeout is None
- custom_id = something_unique_str
then when bot starts view is added with same config/parameters
oh wait component is given custom_id and view is given timeout
so does bot checks for components with that custom_id?
sorry i am struggling to explain the question
Yes, if you use the same custom_id it will "find" the existing component with that ID
so it will send request to discord to give component with that custom id??
can someone answer my quick question about pycord’s voice?
Well no. Rather discord sends a request to the bot every time a button is pressed. Pycord matches the sent custom_id with one that it has stored.
oh okay so discord button in their side also have a custom id thing okay
In theory yes, is it very hard to do, also yes.
thanks for answering, its crystal clear now
yeah that’s what i’ve been struggling with, do you have any recommendations on how to get this to work with each other?
i have them working with each other just not realtime
I have no idea sorry, I have never done anything with voice.
is there anyone in here that could help me out with this?
i know that you can use, some libs to convert, but wont be that great
i think this is what i used
yeah i’m using google’s speech to text, it works after a user has left/moved to a different channel but i can’t figure out how to do it in realtime instead
i know they have a streaming feature
oh i guess it is pycord side, sorry i have never worked with discord voice
yeah same as well until now
it’s been a very long process with getting it to work
This might put you in the right direction. AudioSource.read
If you need more help I recomend opening a seperate thread as this question might take a bit to get help with.
yeah, i’ve tried but nobody has looked into my thread so i just close them, maybe i should keep them up longer
you can also check discord api, who knows whether it can help you
No one here is good at audio/voice :/ . And the person who is best is inactive due to school. It is overall an hard topic
yeah i’ve noticed it’s a hard topic
my friend isn’t available to help either
and it was his idea so i’m kinda in the middle of trying to find out myself
discord api doesn’t have anything related to that i think
It is possible you will need to look through the audio receiving code and make some changes yourself.
yeah, that’ll probably need to happen if it comes down to that which is a pain 😭
i’ll probably have my friend fork it and write something up for it
i haven’t had the best luck it’s been very aggravating to work with even though people make it look easy
but i did get it to work but it only updates when a user leaves / moves to a different channel not (realtime) :/
At least you are close.
yeah i guess you can say that…. there must need to be some changes made to get it to where i want it in realtime. i’ve tried looking at other people’s code to get an idea of how they did it in realtime but there’s no luck
it’s hard to find people who are doing the same thing as what i’m trying to achieve
If you do find out how to to it you might consider making a short guide or something so others can follow you.
yeah because it’s not a difficult task to tackle
but that’s a good idea
i’ll definitely write one up for pycord, since it’s the only thing i could find that has anything to do with “voice”
when a slash command is invoked, ApplicationContext is send in callback, in that do discord send all data about guilds or users? or just id of user and guild?
@client.slash_command(guild_ids=servers, name="pillow_test")
async def pillow_test(ctx, member: discord.Member):
if member is None:
member = ctx.author
img = Image.open("img/welcome.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("fonts/Hanson-Bold.ttf", 40)
# Get image dimensions
img_width, img_height = img.size
# Get text size
text = f"Willkommen {member.name}!"
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
# Calculate coordinates to center the text
x = (img_width - text_width) / 2
y = (img_height - text_height) / 2
# Write Text on Image
draw.text((x, y), text, (255, 255, 255), font=font, stroke_width=1, stroke_fill=(0, 234, 255))
# Save Image
img.save("welcome.png")
# Send Welcome Image
await ctx.respond(file=discord.File("welcome.png"))```
how can i make the text to gradient?
for example red and black or something
no clue directly, but i found this helpful LOOKING Stackoverflow thread https://stackoverflow.com/questions/63246100/how-to-draw-character-with-gradient-colors-using-pil
there is no color attribute for button?
select menus always exist
yea will need to do it like that
its also cool
You could also just use custom color emojis to put onto your buttons
or select menus ig.
can i use role_select and choose what roles should be shown there?
no
only with a custom select menu
with string_select?
does anyone here know anything about pycord voice and if it can handle realtime transcripts with google speech to text?
Yes
anyone know why im having Unknown interaction errors even though im deferring every command
is defer the first thing you do?
yep
then i'm out of ideas without seeing sum code
@bot.slash_command(name = "find", description = "Find an item")
@option("item", description="Item to search for", autocomplete=get_items)
async def find(ctx, item: str, sorting_method: discord.Option(str, description="Method for sorting results", choices=['price', 'scan time']), accessibility: discord.Option(str, description="Whether you can access the vending machine or not (or both)", choices=['path', 'no path', 'all']), min_price = discord.Option(int, description="Minimum price for an item (optional)", default = -999), max_price = discord.Option(int, description="Maximum price for an item (optional)", default=999999999999999)):
await ctx.defer()
con.cmd_refresh(1)
if check_user_int_role(ctx.user.id) >= roles["Per Search"] or check_user_int_role(ctx.user.id) == roles["Trial"] or ctx.user.id in admins:
# MORE CODE HERE
paginator = pages.Paginator(pages=embed_pages, custom_view=ExportView())
await paginator.respond(ctx.interaction, ephemeral=False)
else:
embed = discord.Embed(title=f"Arcturus by asleepdream - Results for {item}", description=f"There were no results found for this item. Please try again later.", color=discord.Color.red())
await ctx.respond(embed=embed.set_footer(text="Credits to Nexica for the idea and bot layout"))
else:
await ctx.respond(perms_message("use this command", "Per Search+", ctx.user.id), ephemeral=True)
@opal hamlet no clue what it could be 💀
its not on every command usage either
what is con.cmd_refresh(1)?
are you using an async mysql driver?
im just using mysql.connector
I think that'll be the issue
well even if mysql isnt async shouldn't the command still defer without any issue?
no because a different usage would be blocking the execution
i don't use mysql
you either write good code the first time, or it grows big enough until it becomes an issue
fr
it grew big enough to be an issue
I suggest sqlalchemy
or I guess aiomysql if you don't want to rewrite your whole bot
yeah i'd prefer not to
you probably already did, but vscode has change all occurences
just to make you realize you wasted your time, now suffer /j
Hey, sorry if the question is dumb, but when I simply copy the code out of the pycord doc, it won't work.
This doc (https://guide.pycord.dev/interactions/application-commands/slash-commands)
When I copy the first code, it will say this:
Traceback (most recent call last):
File "C:\Users\nonoelmo\PycharmProjects\PolyBot\main.py", line 3, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
Can anyone help?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
?tag py-cordnotpycord
No tag py-cordnotpycord found.
?tags
you're not using pycord
yt-tutorials, youtube, xy, wavelink, virtualembed, usernames, usercmd, update, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, this, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, slashblog, rie, restartcmd, requests, replit-install, replit, removeall, pythonversion, pythonserver, python, practices, pp, pomelo, persistant_view, paste, partial_objects, oracle, option, oop, om, official, objects, notpycord, norepl, nojson, nohelp, nohello, no_status, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, logging, localfile, learnpython, json, intents, install_slash, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, git, getalpha, get_x, get-help, gather, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, cmd-limits, closing, client, chatgpt, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, 429
?tag notpycord
The official name of the library is py-cord. When installing the library use py-cord, pycord (without the hyphen) is a completely different package.
this?
okay
what IDE are you using?
PyCharm
what is your list of python packages
idk sorry I'm new
there's a button called "python packages" or "packages"
somewhere on the left bottom corner ish
do you want to use discord.py or pycord?
no, pycord is a different library
i think pycord
so you uninstall discord.py, discord, then uninstall and reinstall py-cord
py-cord* important to note
and then i import py-cord and not discord
Hahahah... I tried... many times.
How can i get user`s DM channel id?
or maybe create_dm() method returns the ID of an already existing channel, if there is one
?
discord.User.dm_channel returns a discord.DMChannel object
oh, okay
ty
didnt see this attribute here ._.
im blind
hi blind, I'm squid
What happens if I use this method when the channel already exists?
you mean doesn't exist?
then it will return the object?
then it doesn't do anything
k, ty
It creates a black hole and destroys discord, be very careful
Idk why, but nothing is said about this in the docs
You shouldn't even call it
Just use dm_channel
so i can get NoneType
Alright, question.
ofc i already did
Select.callback seems to be triggered only when the number of selected values falls within min and max values. How do I get it to be triggered the rest of the time, too?
just dm_channel = message.author.dm_channel or await bot.create_dm(message.author)
thats sounds weird, whats your code
it should get triggered on min and max too
I've got my own sort of system where the embed updates to guide the user on what values may be selected and it isn't being triggered unless the callback is triggered.
But it's not getting triggered above the max.
Here, look.
Hold on, give me a minute, I'll show you.
Except that you can.
It'll just bitch about how you can only select 2.
But it won't actually stop you from selecting more.
so your max is 2
So, the Submit button gets refreshed when the number of values selected falls within acceptable limits (in this case, 0 -> 2).
Correct.
But it allows me to select more than that, and when that happens, Select.callback is not triggered.
And therefor, Submit does not refresh.
Let me say, I don't have an opinion on whether or not Select "should" allow you to select more options than the max.
The two fixes, as I see it, are:
- Call Select.callback on any modification of Select.values
- Disallow selection of new Values after hitting the max.
Either way would fix this, and it doesn't even need to be a library update.
I'll just throw in whatever into my local copy of Pycord.
Whatevah.
Or maybe some third option! Maybe a bool that gets passed to the Callback named "valid" that tells you if the currently passed-in options are within parameters, if you can't stop the user from passing in invalid ones.
Who knows.
i thought discord would just restrict you from selecting more options
Maybe.
Actually, let's do some investigation.
Maybe it does, on other Selects. Let me try on string selects.
Yes!
...But only in String selects.
With Channel, it will simply chide you for breaking the rules :(
Please don't select 3 :((
Now, I know String selects play under totally different rules than the other ones.
But is it possible to modify this behavior to bring them in line with String select in this case?
Could it be some oversight in the library versus a limitation with Discord?
Why am I getting this error? I can send messages to this user, they are even sent, but the error is still there
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
Isn't that only for Paginators?
wdym
interaction_check is a func in the view class
generally used to check authors
Is. That. So.
Perfect.
Then I'll just rewire my logic to trigger on that, instead of on callback.
I spoke too soon. View.interaction_check() is evidently not called upon passing in invalid options.
So it's not that it's screening it out from reaching Select.callback, it simply isn't receiving the interaction at all, TO send it to the Select.
I guess that's all that's left.
There's the @default_permissions(...) decorator. Is there one that lets me specify a role instead?
i didn’t do it yet, but i’m doing each one manually because i got a bunch of different types of sql queries
Only permissions
The idea is that the server admin specifies a role in the integration settings so that the bot does not have to check for it.
There is commands.has_role however this is an internal check, so a user will still see the command even if they do not have the role (unlike when a server admine uses integration settings)
Yeah, I’m aware of that option and limitation. My users have slightly more complex needs than the Discord permissions system. Oh, well!
My solution should still work fine
Thanks
is there really only one person in here who knows anything about pycord voice? 😭
im having weird errors when i switched to aiomysql
Task was destroyed but it is pending!
task: <Task pending name='pycord: on_interaction' coro=<Client._run_event() done, defined at C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:370> wait_for=<Future
pending cb=[Task.task_wakeup()]>>
Ignoring exception in command find:
Traceback (most recent call last):
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
RuntimeError: coroutine ignored GeneratorExit
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: RuntimeError: coroutine ignored GeneratorExit
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
my command code
how do i know whether a custom_id exist?
I mean what if server moderator or someone deleted the message that has that custom id
i can't seem to accept attachments in slash commands, someone show me an example, can't find it in the pycord docs
(ctx, file: discord.Attachment):
oh
ok and how do i access that file
attached by the user
just file?
nvm i kinda got it working
I cant run my application ._.
When I launched it, it worked as if I had launched it somewhere else
So I reset the token
and now cant run it
discord.errors.LoginFailure: Improper token has been passed.
how to fix it
oh
u just cant run any application
i can run it on website
but cant run it local
ima try to reinstall pycord
still doesnt work
but i can run it in default python console
but not in pycharm
this code was working just yesterday
what happened meanwhile i was sleeping lol
@commands.Cog.listener()
async def on_message(self, message):
if message.type == discord.MessageType.stage_raise_hand
I assumed this would fire on some kind of invisible system message that was created when someone raised their hand, but this is not the case. Any clue what I can do to hook the "user raises hand" event?
What are your intents?
bot = discord.Bot(intents=discord.Intents.all())
does py-cord support python 3.12?
you really should wait with 3.12
I use currently 3.11 and there are many librarys who are still not working with 3.11
I wonder even what type event that is?
so 3.11.6?
or 3.11.5
cause 3.11.6`s realese date is same with 3.12
11.6 should be fine
how do i choose only some specific intents i need?
intents = discord.intents.none()
intents.message_content = True
like this
thanks i was using + 🤦
u also can use .default() instead .none()
if u need all default intents
for now i am only enabling those intents which i need
I would do ```py
intents = discord.Intents()
intent.message_context=True
Guys, help. I'm trying to make a music bot, but there is one problem with FFmpeg
The point is that I use Replit for writing code, including running the bot, and I also do everything from my phone, but as I understand it, I need to download FFmpeg , what should I do?
u dont have PC?
I think you can use python-ffmpeg or shit which you can install via pip, i assume replit allows that as you can use py-cord (never used replit, so dunno)
You dont really. You could save the message ID of the message with the component, Then you could check if the message exists ever x amount of time (like month or something)
I guess you could catch it in on_message_delete but if you lose access to a channel before it is deleted or something.
Understood thanks
oh okay
An Unknown interaction error occurred in await ctx.defer(). How is this possible?
Error at the code?
is it because he replied to that?
quick question, how can I integrate autocomplete with options? for example, in autocomplete, i have type 1, type 2 and custom as the options. if the user chooses custom, the user should be able to type in whatever they want.
is that even possible in pycord, i tried a lot
Yes
Perhaps my laptop is so weak that it cannot execute the algorithm defer() quickly
Task was destroyed but it is pending!
task: <Task pending name='pycord: on_interaction' coro=<Client._run_event() running at C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:378> wait_for=<Future pending cb=[Task.task_wakeup()]>>
im getting random console logged errors like this
i had this issue when i was using a non-async mysql driver and the query was blocking (and blocked simultaneous command usage)
check if you have anything that blocks
Is ctx.defer the first line at your code?
Yes
So there are obv. The @commands.has_permission(administrator=True) and @commands.is_owner decorators for slash commands, but can i make it so that it is for server admin OR bot owner
Sorry for the misunderstanding. If you want to use the name variable inside the class, but outside of any function or method, you can do this If you want the name name it, creating at variable by creating an at to be available inside the class. Here's how to do it:
python
Copy code
class MyClass:
def __init__(self, name):
self.name = name
# Creating a class object and passing the name
my_object = MyClass("Name")
# Access to the name variable inside the class, inside the class, outside the function or method
aprint, but outside(my_object any.name )
In this case, the variable nameb becomesyao functribute of the class and can bee, you can define it as atri accessibble insi the classout,ri and not the class aat inidse the functiobut eik eliz methodovem.p
Chat gpt, what`s wrong with you lol
so guys
how can i transfer any parameters in button? when u subclassing discord.ui.View, u must write buttons via decorator, but u dont have access to self in main of class
for example:
class MyView(discord.ui.View):
def __init__(self, button_label):
self.button_label = button_label
@discord.ui.button(label=??button_label??, style=discord.ButtonStyle.blurple)
async def callback(self, button, interaction):
await interaction.response.send_message('hello')
that is already a button class
why do you create a new button in it
Do you understand how OOP, specifically inheritance works?
i wrong with subclass
i mean discord.ui.View
i just made a typo
so how to do it?
create a discord.ui.Button object or subclass discord.ui.Button
there is no way to do it via subclassing discord.ui.View?
okay
what are the reasons a slash command isnt appearing?
Hi, please tell me why I cant get the global nickname of a participant when he connects to the server?
Instead of a nickname, it gives username(@username) or None. =((
What is your py-cord version?
Latest
self.clear_msgs.name_localizations = {locale: Localization(locale).clear_msgs.command_name for locale in locales}
self.clear_msgs.description_localizations = {locale: Localization(locale).clear_msgs.command_desc for locale in locales}```so i am (successfully) using this to localize my command name and descriptions, but how can i localize command Options such as amount ```py
async def clear_msgs(self, ctx:discord.ApplicationContext, amount: Option(int, description='The maximum amount of messages to clear.')):```
should i just declare a variable for it in my __init__ instead and just using that in the Option()
I usually would use @discord.option() for option stuff
well never used that decorator, gotta
but still, how would i acess that then? self.clear_msgs.option('amount').name_localization or smth?
someone please help lol
i can't seem to figure it out
is there a rate limit for calling sync_commands? having the issues that the command options only load when the bot is ready so i put it into on_ready, but if i then assign it they have already been synced in on_connect with the placeholder description
100 application commands per day
A total of 100 refreshs for all commands or 100 commands that can be synced, but more than 100 times a day
Because well, durinf testing i kinda need a few syncs 😅
Im not 100% sure if you sync the commands that they would send a new api call for the command
Well maybe i should just override the on_connect command sync to disable it
And just do it manually
Atleast the localization is working (thanks bing)
not this, im talking about user input
like if the user chooses the custom option, they should be able to type in whatever they wnt
want
i need like an example or something
You have 2 options
- With autocomplete the user is not forced to select an option. You could just have them type in anything and not have to select
custom. - When
customis selected send a modal.
Here's the modal dialogs example.
🤔
thanks a lot
when the user chooses custom, is it not possible to open up a user string input
As in another option, No. Slash command options are static. You could add an custom_text option and just ignore it unless custom was selected
yes i think thats what i'm trying to do. can you show me a small example on how that can be achieved
Just add another discord.Option
Then do
if type_choice == "custom": type_choice = custom_text
Can you decorate the same method with multiple listeners, e.g.
@commands.Cog.listener(name='on_member_update')
@commands.Cog.listener(name='on_user_update')
async def member_change(self, old_member, new_member):
...
or what's the best way to capture all user modifications? I can't tell whether something with the username system is causing me to miss some events, or what, but some banned names are getting through and I can't tell how.
Can I make a paginator responsive without adding a custom view and custom buttons to the paginator ?
class PaginatorView(Paginator):
def __init__(self, bot: discord.Bot, card_info):
self.bot = bot
self.pages = self.create_pages(cards_info)
super().__init__(
pages=self.pages,
use_default_buttons=True,
timeout=None,
author_check=False,
)
how to get thing like this?
so if u just use await ctx.respond(attachment)
u get this:
you can use the file or files kw-argument
so i must download it first?
and then send
right?
I don't know the nature of your file so maybe?
i cant do it with url only? like file = discord.File(url)
you could just send the url
is it possible to create custom conditions for slash command to be visible?
no
what about allowing it to only specific user by userid?
you can do that manually through the "integrations" server-settings tab
is there a way to do it with bot?
yes, it just involves oauth2
simple if you've done it before, tad complicated if not
ok ty
I get this:
Do you need to use ConnectionPools with pycord ? If I use normal connection for a mysql database, I get Internal errors with sequences number of packages. From what I am seing, it can happen with multiple threads and the solutions is a connection pool. But I though with asyncio, there was only 1 thread that is switching between task ?
is it possible to pass a data value like attrs below to discord.Interaction using discord.SelectOption?
I wanted to update the embed showed in a discord.ui.View using said SelectOption but the data class is local or inside discord.ui.View class
@define
class Values:
id: str
name: str
...
Where is the data coming from and what are you using it for?
I don't use sql, but ive seen most users use a connection pool
from API that returns typical JSON string as the data.
I wanted to use that data to make an embed.
Something like
Select option > callback > HTTP Get > fancy function > data becomes embed
Hello everyone !
I have a quick question, do you know any ways or library that could help to do automated tests.unit tests for pycord bot ?
I found some but they are meant for dpy :/
The biggest issue is that most of my commands call a database and sends embeds so i don't really know how to ensure the results are correct
whats the command for the persistent view example again
wasn't there a command tho, but thanks
yea but I cannot see the slash commands
god im fucking stupid i don't even need that rn ... an embed isn't a view
yeah that's why i asked heh
make it so the only way to change the variable is through a function, then add whatever functionality you want to that function
issue is, I want like a seperate window where I can just type things
and it sendsto the bot, and sends to a predetermined channel
like an InputText Modal?
In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
It is often used for implementing distributed event-handling systems in e...
this may help you
bad representation but
input in 1 window, bot processes it, and sends a message to discord
another terminal window
so
terminal.py -> main.py -> discord
hmm
preferably without bot restarts yk
terminal.py can just be a basic terminal application where it constantly asks for an input
So the data you get becomes options for the select menu?
yes, basically a
while True:
variable = input("> ")
you could make a function in your bot that receives a message and just sends it to a channel
import bot
while True:
variable = input("> ")
bot.sendMessage(variable, channel)
that's pseudo code, right?
yeah
No. I wanted to use select option to update the embed based on the data that I already have.
say I have ClassA and inside it there's a list of Students. I wanted to change the embed per student using Select
import bot
while True:
variable = input("> ")
await bot.sendMessage(variable, channel)
the while input halts the bot
no?
no it shouldn't
at least i dont think so
Why cant you just pass the data to the select/view class?
# terminal.py
import bot
while True:
variable = input("> ")
await bot.sendMessage(variable, channel)
# bot.py
import discord
import utils
async def sendMessage(self, message: str, channelID: int):
channel: discord.Channel = utils.get_or_fetch(self.bot, "channel", channelID)
channel.send(message)
something like this @autumn gust
It does, unless you do it in a separate thread
hmmm
god I forgot about it and it made me wheeze
I did. but that way I cant update the embed since the interaction doesn't pass the data.
actually I just remembered that I haven't tried using index as SelectOption value and use that to set the embed. I'll try this first and come back if it failed 
# bot.py
import discord
import utils
import asyncio
bot = discord.Bot()
channelID = 0
async def terminal():
async def sendMessage(message: str):
channel: discord.Channel = await utils.get_or_fetch(bot, "channel", channelID)
await channel.send(message)
while True:
message = input("> ")
await sendMessage(message)
asyncio.run(terminal)
bot.run(os.getenv("TOKEN"))
@autumn gust
try this idk
Is it possible to end a users stream?
You cannot do that, unless you kick them from the voice channel I suppose.
Im not sure if this is possible but; You could try to move them to a channel which doesn't allow users to stream (in which case their stream might be ended?) and then you move them back to the channel while them not streaming anymore.
if you move them at all the stream will end
Oh-
how can I allow command usage in DMs
Does it even need to be allowed?
Doesn't it work by default unless you set them to guild only
They already work by default
Unless you use a decorator guild_only
Hi !
I would like to know if it's possible to interfer between a ctx.respond(...) and the moment its completely sent to discord in order to check the values ?
I would like to avoid any package modification and if possible to stop the sending
Hello
Can I use folders to create command groups, and the python files in it are commands
for example:
if i have three folders:
- admin
| - ban.py
| - kick.py - music
| - play.py
| - disconnect.py - game
| - 1a2b.py
| - tictactoe.py
I want it to be like this
/admin ban
/admin kick
/music play
...
thank you
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...
It would not work be default with folders. You would still need to create the group and add the commands.
You might be able to override Bot.get_application_context with a subclass of ApplicationContext
after i unlaod cogs, im trying to make sure you cant run any of the commands,
async def cog_before_invoke(self, ctx):
cog_name = ctx.cog.__class__.__name__
print(f"Checking if {cog_name} is in {self.bot.loaded_cogs}") # Debug print
if any(loaded_cog.lower().endswith(cog_name.lower()) for loaded_cog in self.bot.loaded_cogs):
return True
else:
await ctx.respond(f"The cog {cog_name} is currently disabled.")
raise CogDisabledException(f"The cog {cog_name} is currently disabled.")```1
idk whats wrong with the formattign, but, im unsure how to achieve this, ive been trying the cog_before_invoke, but the whole issue is the only way ive managed to get it not to try to invoke the command is by using raise, but then teh issue is, it prints out to my terminal the error which i dont want it to
class CogDisabledException(Exception):
pass
im so lost on how to achieve this
Well you can put it in a try except and then just pass in the except
Actually I think that would just continue execution because the exception is caught
Maybe you can try adding a on_command_error, check if it’s the disabled error, then handling it accordingly
How can I make a message ephemeral when using interaction.followup.send()?
Isn't it already that if the first message was ephermeral?
So the first message has to be ephemeral?
Dont think so
Just pass ephemeral=True
it can only be ephemeral if it is a followup to an ephemeral defer
I was looking for that in this documentation but didn't see it. Unless I'm looking in the wrong place
So I can't have a non ephemeral defer with an ephemeral followup?
yes
Damn. Honestly these should all be ephemeral anyway lol
do views inherit the params that the slash command has?
for example : if i have a slash command with a users id could i use it for a button response?
For a check or what?
if you know how classes work, that should be simple
Welcome to basic OOP
So what?
Its still a variable.
You just pass it to the view which you previously defined with the appropriate init
*argument
Argument deez nuts
?
Geh schlafen
I need to read a book first but it's so fucking lame I don't want to
Can my button label contain alt+0160 ? It's the windows invisible letter
.rtfm message.channel_men
hmm
So I have a bot and it can take messages if u dm it, but if u message in a server it logs the channel and the username but not the message content and I am so confused
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
this is how I extract the information and like I say it works in dms perfectly but in servers it doesn't seem to get the message.content correctly
it just saves user_message as , nothing
no matter what the message is and no matter where it is
the bot has administrator permissions and access to all the channels so its not something to do with roles or permissions
Youre missing intents
?tag intents
Pycord Docs - Intents
Discord API Docs - Gateway Intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
how can I allow commands in dms? i was told before they work by default but I can’t use any commands from my bot. Maybe it’s because I defined servers in the code?
slash or prefix commands?
I already have intents which is why I am so confused
In your code and the dev portal?
yep
Show your code
# Discord bot
import random
import discord
"""
Invite Link =
Token =
"""
intents = discord.Intents.default()
async def send_message(message, user_message, is_private):
try:
response = handle_response(user_message)
if response:
await message.author.send(response) if is_private else await message.channel.send(response)
else:
print("Empty message?")
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = ''
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is now running')
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
await send_message(message, user_message, is_private=False)
print(f"{username} said {user_message} in {channel}")
client.run(TOKEN)
def handle_response(message) -> str:
p_message = message.lower()
if p_message == 'hello':
return 'Hey there'
if p_message == 'roll':
return str(random.randint(1,6))
run_discord_bot()
The token is there in the actual code, I just removed it cause yk
you need to include message content intent in your code and enable it in the discord application settings.
default() alone won't do
Now its saying that it doesn't have intents enabled on the dev thingy but it has all of them ticked
Hello,could anyone help me there?
https://canary.discord.com/channels/881207955029110855/1162369021790920745
What about the sliders ?
sliders?
this is the error
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
there, those sliders
thats were you manage privileged intents
How do you get to that page, im sorry for asking all these questions
Don't be, you're in the help section 😄
You know where you made the invitation link for your bot?
there is a menu on the left named "bot"
that's were you find the sliders
I knew I saw it before ty
mind if I ask if you intend to make your bot publicly availible or if its just for personal use?
good. In this case there should be no worries about the intent settings in the long run.
tysm
is it just me or @commands.has_role is bugged in Cogs?
command: (in a cog)
@commands.slash_command(name="ghostping", guild=guild, description="Ghostpings the user.")
@commands.has_role(item=admin_id)
async def test(self, ctx: discord.ApplicationContext, user: discord.SlashCommandOptionType.user):
await ctx.defer(ephemeral=True)
await ctx.interaction.response.send_message(content=user.mention, delete_after=0.3)
Error:
Role '' is required to run this command.
what is missing_role?
as per the docs, commands.errors.MissingRole.missing_role should return the role that is missing
you could just do e.missing_role.mention
than you dont need the <@&> stuff
as i have that role
@little cobalt so turns out i was using <@&> because it doesnt return a role
but the id of the role
and it also asks for the role
could it be that has_role(id) just tries getting the role from cache?
and because it doesnt find it, returns None
?tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
thats exactly what im saying
it doesnt have the role in cache
ye
but @commands.has_role might try getting the role by the id from the cache
@commands.is_owner() works as intended
seems like it was an issue on my end
i have a function that has to get awaited. but its called inside of a @bot.command. and that causes alot of errors.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: asyncio.run() cannot be called from a running event loop
Hello there. Is there a way to make an ui.Select component narrower? In order to fit 2 in one row? I guess not but just wanted a confirmation.
could you send a code snippet?
async def getreply(message):
from g4f.Provider import (
AItianhu,
Acytoo,
Aichat,
Ails,
Bard,
Bing,
ChatgptAi,
H2o,
HuggingChat,
OpenAssistant,
OpenaiChat,
Raycast,
Theb,
Vercel,
You,
Yqcloud,
)
response = await g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
provider=Aichat,
messages=[{"role": "Admin", "content": f"{message}"}],
) # alterative model setting
print(f"SUPPORT TEAM: {response}")
return(response)
@bot.command()
async def request(ctx,*,helpx):
response = await getreply(prompft)
await ctx.reply(response, mention_author=False)
slash
did you define the guild id?
whitelisted_guilds = [int(config["SETUP"]["server"])]
bot = commands.Bot(debug_guilds=whitelisted_guilds, intents=intents, command_prefix=".")
can i get a user's discord language while he use a slash command?
That's a thing?
no it's made up 
Fk off 😂
gatekeeping
Hi, is there a way to update custom view in Paginator after switch the page?
Could anyone help me?
https://canary.discord.com/channels/881207955029110855/1162369021790920745
what's the issue here?
"discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 40067): A tag is required to create a forum post in this channel"
@bot.command()
async def thread(ctx):
forumChannel = await bot.fetch_channel(CHANNEL_ID)
await forumChannel.create_thread("test", content = "test")
how do I add a tag?
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 ...
You can use applied_tags
how do i get the tag ids of a forum?
You can use https://docs.pycord.dev/en/stable/api/models.html#discord.ForumChannel.get_tag to get tags by id
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 ...
or to get all tags: https://docs.pycord.dev/en/stable/api/models.html#discord.ForumChannel.available_tags
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 ...
can someone have a look my thread #1162830037758783588 ?
that works, thank you!
forumChannel = bot.get_channel(CHANNEL_ID)
tags = forumChannel.available_tags
print(tags)
looking through chat history honestly really painful so i hope that putting my solution here helps some poor soul LOL
how do i send a message to a thread given its id?
thread_id = applicant[0].thread_id
#send message to thread
forumChannel = await bot.fetch_channel(FORUMCHANNEL_ID)
thread = forumChannel.get_thread(thread_id)
await thread.send(f"{ctx.author.name}: {ctx.content}")
gives me a AttributeError: 'NoneType' object has no attribute 'send'
thread_id is outputting the correct integer of the thread
ah nevermind i answered my own question
checked the type and it was a string 
Is a autocomplete like the one YAGPDB bot uses possible with Pycord and what do I need to do to add it to my slash commands?
No, thats a member option, not an autocomplete
okay, what do I need to use it, I have been banging my head with autocomplete so this revelation is great
You just typehint discord.Member
async def my_command(ctx, user: discord.Member):```
Okay cool, thanks for help Dark
hello, how get pages.Paginator in custom_view? This code doesn't working
paginator = pages.Paginator(pages=pagess, disable_on_timeout=True, timeout=30,author_check=True )
paginator.custom_view = GoToPage(pag=paginator)
class GoToPage(ui.View):
def __init__(self, pag):
self.pag = pag
@discord.ui.button(label='page')
async def page_to(self, button, interaction):
await self.pag.goto_page(10)
it returns AttributeError: 'GoToPage' object has no attribute 'children'
after creating a button after some time it stops working even if the bot has been running the whole time
ooooh
thanks
is it just timeout=None
?
View class and add_view
do i have to remove view somehow?
you have to use a view class
yea i added this
im adding add_view now
how do i remove it?
after i want it to end
just delete the msg?
or view
what?
add_view Registers a View for persistent listening right?
yes
after pressing the button?
im clicking the buttons multiple times
i need it to be able to respond after some time
you could increase the timeout time of the button
but they are not gonna work after a restart then
thats ok
timeout=the seconds
i dont need it but if i do is there a way?
you could create your own "handler" for the time which would disable the stuff
ok
How could you check if a channel exists in your discord server?
.rtfm guild.get_channel
how to set slash commands?
what are you asking for
i want setup slash commands in my bot
you can check out the guide for basic information
like that
?tag guide
Official Pycord Guide: https://guide.pycord.dev/
can u send me link of example code (slash commands)?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Cool! Thank you! ❤️
it don't work, i am using it in DM
did you set any guild id?
nope
can you press ctrl + r for a client refresh
still not work
`import discord
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command(description="Sends the bot's latency.") # this decorator makes a slash command
async def ping(ctx): # a slash command will be created with the name "ping"
await ctx.respond(f"Pong! Latency is {bot.latency}")
bot.run(mytoken)`
if you are using commands.Bot, you would use @bot.slash_command() instead
change it to discord.Bot or change it to bot.slash_command
@bot.slash_command(description="Sends the bot's latency.") # this decorator makes a slash command
AttributeError: 'Bot' object has no attribute 'slash_command'
can you show the pip list?