#General Help
1 messages · Page 7 of 1
That doesnt work the same for Slash Commands
it does work on slash commands, but it's an internal check
you can no longer implement discord-sided role/user checks from the bot, it can only be done via the integrations tab
which is why permissions.has_any_role and similar decorators were removed
bot.voice_clients
working fine for me on rc1, don't think they were changed either
Yeah but I needed to check in one guild regardless of a channel which each voice client didn't have, forgot I have a channel from the bridgeContext so I just got the guild and checked the state of the voice client
fair enough i guess
@bot.event
async def on_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
print('test')
embed = discord.Embed(title='Error Handler Module', description='**Why did this happen?**\nThe command you attempted to run is an admin only command and as such will not execute!', colour=discord.Colour.purple())
await ctx.respond(embed=embed)```
When I run an admin-only command, i still get the error in my terminal and an embed is never sent nor is test printed
I'm working on a system that whenever it detects that someone has like ads in their status it removes some roles, that's done but now I want to give them back too when they remove their status and the bot wouldn't know who ppl are staff and who aren't so it might just give staff to some random ppl who had ads and then removed it so I want to make it so that whenever the user removes ads it gives back the roles it removed.
maybe because you have your own checks? if yes do commands.CheckFaliure for that command, tbh just check it using the command itslef
I highly suggest to create a database in order to keep the roles ID they had and just fetch them whenever they remove it
on_command_error or on_application_command_error
make it so that if this user has the role or whatever they can run it else bye ybe
Yeah well I don't really want to make it this complex tbh
Do you have another way to save what roles they had?
^ you need some way to save it externally
idk maybe a json file since its not gonna be that big(I think)
if it is prob a sql db
Ofc it's one way
But in a database the data will be highly easier to access
I really suck with dbs.
a db would be ideal, but if it's on a small scale then a json will suffice
Here are your options:
- database with mysql
- json file
- gspread
gspread a google spreadsheets api that will help you to store data
Used it and it's great, before I paid for external database
why can't I go with a SQLite3 file?
Actually, you can do it with .db file, i think it's doable
I mean I'm actually working on making a warning system with PostgresSQL
Yep.
Or I can use .sqlite3
Same thing, mostly.
Or that
there's nothing stopping you
xDDD
The thing is, I know like nothing about dbs.
Ah thanks, that was the issue
so that's why I'm here.
There you go, something to learn
I've been trying to learn for a month
Always learn new things that will help you in the future 🙂
Took me same time to learn how to integrate any db with python
It's confusing at first but it's just query with a command executor
Are you building any large-scale bot?
for now I can just scrap this for now
It's a private bot
For one server, not much
That's why I'm saying I could indeed use json
yeahhh
but I'm expecting the server to get really big
Probably.
(I don't know how to implement this into it)
Like I know how to use JSONs but idk what to do
I have a great site for it gimme a sec
I'm saying like what inputs should I do.
I know how to do stuff with JSON
Like what should I do?
Make a list? or in a dict I make a name with the user's id and then the value would be the role ids>?
idk what to
dude im just gonna scrap this I expected this to be like a 1-2 hour project and ive been doing it all day lmao
Like that:
member_id: [
role_id1
role_idf2
]
(Doesn't know how to give the roles back)
member.add_role(id) I think
I know its add_roles but uh, how tf would I do it ;-;
bot.get_role
dude I know how to give it back, if I didn't i'd google it or look at docs
OMG but
how do i get the value
like how do u get values from json from dicts
ik u can just do dict_var["thename"]
ye
okay my neice is typing stuff brb
Okay i'm back
k
I dont really need exact code but the steps I need to take to do this. How do I make a verification bot work the way thinks like carl or verification bot do? With those images and everything
okay so
there will prob be more than one role
with open("roles.json") as f:
dict = json.load(f)
values = dict[str(after.id)]
for i in range(len(values)):
```
and im doing this
and I should prob define variables with a number or do I just define em and then get it?
actually nvm fixed my prob
So you want something like this? Just instead of this message to be verify process
Don't know if you know but you can use pprint to output it nicely to the json file
Not reaction roles, lemme get an ss
Yeah that'll help actually
using indent=4 ik
Okay nice, great
Okay got the stuff working, how do I check if the status is nothing? cause its actually a tuple I think
Never learned about the status thing, never got the chance to
If you say
docs say so
I cant find an example so heres my terrible ms paint example
how do I check if theres no more ads in the status?
artist for sure, idk what you want still sry 😄
I can't just check for a empty tuple as ppl might their status with something else
than just keep it empty
sooo what do i do
okay well, the numbers are randomly generated, the user has to type out those numbers that have lines on them and there will be bait numbers in the background
OOOH like reCaptcha?
yeah
YEQAH
bruh the painting
i want to make my own for customizabilities sake
yeah yeah ik
There's also a bot to stream music and I'm still doing one xDDD
yep
.
Yeah I'm not it
cause I don't know how to do that im stupid
can u just check me if there is not a perticular thing in a string
like can u help me check if theres no "discord.gg/" in a string
Check for status, if there's a status you can check if it contains a link to another discord server which is not yours aka invite link or custom link
thats simple python
dude ive done that already
now I need help if someone has removed the ads from their status
cause we can't rely on everyone just removing their status they might change it to smth else
like have ads at start, then change it to "hey" or smth
Maybe do on status update? if there's an event like that
wait I already have the thing where it checks for it
so can't i just use an "else" statement
like if its in there alr else u got ur roles back
About you, I think you can do it with regex to generate it for you
Like a pass generator
h o w do i put stuff inside of it now, ive did the thing where it takes data and gives roles back but how do I put the role ids in the dict?
Im more concerned about getting the numbers on the image itself
loader[member_id] will return the list
the generation is fairly simple but not sure how I put those numbers on my image
Yeah, gimme a sec I think there's an actual api
ooh thanks
Found it
# Import the following modules
from captcha.image import ImageCaptcha
# Create an image instance of the given size
image = ImageCaptcha(width = 280, height = 90)
# Image captcha text
captcha_text = 'GeeksforGeeks'
# generate the image of the given text
data = image.generate(captcha_text)
# write the image on the given file and save it
image.write(captcha_text, 'CAPTCHA.png')
Is that what you meant?
instead of the dict file remember the json object gives you exactly that so you can use the member_id the fetch the removed roles
thanks so much!
No problem, ping me if you need anything else
ofc tyvm
what to put inside of it
like how to make the list
{
id: [
role1,
role2,
]
}
If that's your list then when you do json.load(file) then you can just use loader[id], it'll give the list
hey how to do it INSIDE OF IT
like I know what to do manually
I need it to do it automatically
or I might aswell not make the feature
the thing is, not everyone has certain roles
most ppl dont have staff roles, so when they do(I have a check if they have staff role or not) I want to add that in too
whenever you remove the role and get it's id you just put it inside a list and dump it to the json
idk how to dump a lot of ids that are from different checks at once.
its like
ok yeah time to add this to it
if this user has this special role:
add this to the db
whatever...```
give the json more options like:
{
id: {
staffRoles: [],
roles: []
}
}
If u have more options you can just put the member_id as it's own dictionary which will indeed help you out
remember it's your code
And?
so make a new thing for each of em?
if have_ads():
role1 = member.remove_role()
updateRoles(role1)
You don't have to do for each role a check
uhm what if they dont have that role
Just one function if it's a stuff role ( yes you'll have to do a list that contains all of them as you decide cuz discord roles has no groups ) and one for regular ( anything not in the list )
that'd just give an error.
if role in ctx.author.roles:
do stuff
Pycord gives you a lot in terms of clean code ( one of the main reasons I switched a few days ago ) and efficiency
One message removed from a suspended account.
tasks.loop
One message removed from a suspended account.
I do that already?
One message removed from a suspended account.
Then you check if they have the roles
So you remove it?
oh
and add to db but idk how
if activity.name.startswith("https://") or "discord.gg/" in activity.name or ".gg/" in activity.name:
print("This is the longer if statement, it has detected ad")
# Check for roles
if member_role in after.roles:
await after.remove_roles(member_role)
if staff_role in after.roles:
await after.remove_roles(staff_role)```
how to add the stuff after I remove too?
with open("file.json", 'r') as f:
loader = json.load(f)
loader["something"] = [] # data you want to dump instead
with open("file.json", 'r') as f:
json.dump(loader, f)
I think it'll work cuz when you dump the files it'll overwrite
dude
im not asking for this
im aksing how to input the stupid role into it
because in each check I have to do that
and if theres a value there i dont want to overwrite it
yep
🙂
If you ever feel stupid you forgot ask an html coder how to center a div
They'll check it
xDDDD
hope im not bothering you!
# Create an image instance of the given size
image = ImageCaptcha(width=280, height=90)
captcha_text = random.randint(120000, 999999)
# Image captcha text
captcha_text = str(captcha_text)
# generate the image of the given text
data = image.generate(captcha_text)
# write the image on the given file and save it
image.write(captcha_text, 'captcha/CAPTCHA.png')
await person.send('Go ahead and type what the captcha sent below has. Do not add any spaces, if your answer is wrong, you will have start the process again!.', file=discord.File("CAPTCHA.png"))
print(captcha_text)
msg = await bot.wait_for("message", check=lambda check: check.author.id == ctx.author.id)
print(msg.content)
if(msg.content == captcha_text):
await person.send('Correct! Role should have been added, if you did not get the role, please contact Powerhouse_')
else:
await person.send('Incorrect, run /verify again.')```
The check runs even if the message wasnt sent in dms, how can I make a check for that?
In discord.py I used wait_for so he can wait for a dm back
IDK how to do that in pycord
im also using wait_for but if a message is sent by that user in a non-dm channel, it still registers it as an answer
You want it to be sent in a dm or in the channel?
dm
the bot dms the user with the verification process
but if the user sends a message in a different channel, it still registers that message as an answer
Gimme a sec
alr
def make_sequence(seq):
if seq is None:
return ()
if isinstance(seq, Sequence) and not isinstance(seq, str):
return seq
else:
return (seq,)
def message_check(channel=None, author=None, content=None, ignore_bot=True, lower=True):
channel = make_sequence(channel)
author = make_sequence(author)
content = make_sequence(content)
if lower:
content = tuple(c.lower() for c in content)
def check(message):
if ignore_bot and message.author.bot:
return False
if channel and message.channel not in channel:
return False
if author and message.author not in author:
return False
actual_content = message.content.lower() if lower else message.content
if content and actual_content not in content:
return False
return True
return check
This is the functions I did a while back
Like discord.py 1.7.2
Before pycord was even released
So IDK if it'll work now but it used to work
'message', check=message_check(channel=ctx.author.dm_channel)
And this was inside the wait_for
DISCLAIMER: All functions were copied from stackoverflow so I do understand it's purpose 😄
I use py values.remove(i) in my for i loop but it gives me: ValueError: list.remove(x): x not in list I tried doing i+1 and even .remove(1) but its the same
wait shoot
values.contains(x)
values.remove(x)
i accidently replied
I don't use x tho
I use i
but SOMEHOW it just thinkgs theres x
Wait, you remove it by index?
yeah?
If you're looping with a ranged and a list fixed value it'll always be shorter
for i in range(len(values)):
print(f"values.remove({i+1})")
roleid = values[i]
values.remove(1)
role = guild.get_role(roleid)
await after.add_roles(role)```
I tried +1
(ofc in the .remove but its in the print statement cuz yes)
oh lol
the remove is 1 now cause Im just testing if it works
But u always remove and the range doesn't change
it does?
its based on how many stuff is inside the list itself
values = dict[str(after.id)]
i use len(values)
so it changes to however much stuff is inside it
can u just tell me a way to remove everything from the dict when im giving roles back?
list.clear
yeah it's with .clear
Now I need help, is there a way to get passed arguments from a command in a check using the ctx? ( in slash it's ctx.interaction.data but is there a way to do the same for extcontext )
how do i add this to my previous code/lambda in the bot.wait_for
and message_check \
i think ctx.args or ctx.kwargs may work
It said None
there's also ctx.current_parameter if you need that one specifically in your check
Returned empty
might be that args and kwargs are only processed after invocation then
For interaction there's a perfect and simple way but for ctx there's not
Maybe there's no way to do it?
Yeah you were right
thanks tho
Is there a way to check error handling for bridgeCommands?
msg = await bot.wait_for("message", check=lambda check: check.author.id == ctx.author.id)
Soo, how can i add a check for if the msg.content was sent in a dm?
Ctx.guild == None
whats rc1 for pycord guys
release candidate 1
many thanks, that did it for me :D
Welcome
Is there a way to invoke another bridge command?
Instead of retyping everything and such
there's various functions for invoking another command, but you need a valid Context object
one weird hack i like is to grab an existing message, edit message.content to the command I wanna run and then run bot.process_commands on the message but that might not be ideal
otherwise you want ctx.invoke(command) with any other args
Can I set perms for specific subcommands? Or discord limitation
though come to think of it im not sure if bridgecontext has invoke
uhh i think that is indeed a discord limitation
perms are limited to top level iirc
thanks discord
I'll try it actually
For some reason it tells me I don't have an attribute called client
whadohell
Thats so strange, if someone knows please help i'm struggling, using BridgeCommands
init not int lol
BRUH
Okay ok ok
I promise
I'm not stupid
I'm tired af
😦
all good, happens to the best of us lmao
xDDDD
I have a Message Command that calls a Modal. When the Modal is submitted, I need to get the Message it was originally called from.
I tried interaction.original_message() but got an "Unknown Webhook" error.
Is there a better way of keeping track of it? Could I pass the Message into my custom Modal constructor?
(Edit: Yeah, I think that might be the best option; pass in the message to the Modal class; reference as self.message)
What am I doing wrong?
I tried to use the new method for slash command options
Used the officcial example there its also not working,
This one: https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
Is there a way to let the interaction wait for command process to be complete?
What's the difference between discord.Bot and commands.Bot or bot.slash_command, commands.slash_command and discord.slash_command?
Can I get the time from a user?
you mean the timezone?
this may be a start
https://stackoverflow.com/questions/72080488/is-it-possible-to-get-the-users-time-zone-from-author-or-message-in-discord-py
is it possible to get a users time zone from a message or a user if or something like that. For example if I were to say something it would print out my time zone, this is in discord.py btw.
Thanks
I use datetime.datetime.now() at the moment
if you mean a user's timezone, no
should I use utcnow() or now()?
depends on your usecase
i usually use utcnow
just for consistency between machines
think it's an issue with the enum/decorator style options... wooo channel options
not even the tuple version works anymore rip
aaaand discord.channel also broken
at least discord.abc.GuildChannel still works
very much depends on what you need; discord.Bot allows application commands, while commands.Bot adds support for prefix commands
pretty sure all the slash_command decorators are interchangeable though
so discord.Bot doesn't allow prefixed commands?
yep
hm. ok
also if you're using commands.Bot, you need to specify intents for prefix commands to work
and is there any other difference besides of that?
generally just better command management, there's quite a lot in the commands extension that works best with commands.Bot
there seems to be a max limit of choices discord will show when using the autocomplete. What is the size of that limit?
You can read about it at https://docs.pycord.dev/en/master/ext/commands/index.html and https://guide.pycord.dev/category/commands
looks to be 25
thank you
ok, so ext.commands is probably the better option?
for me its +2h
Why do I have to use ctx.respond? Is there more to it other than just replying to the invocation? And why does it say The application did not respond if I don't respond?
If 3 seconds isn't fast enough for you, you can defer the interaction.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
discord requirement
you have to respond to every interaction
to some extent yeah, but it has its own benefits
and you can just make the response ephemeral
Can I respond with nothing?
has to be a message
hm
every command call, button press, dropdown selection, modal submission, and any other interaction you can perform
has to have a message response
well close enough anyway
it sounds strange at first but after actually implementing your stuff it's not that bad lol
yeah I guess that's right
I'm just starting to use the interaction stuff...
I like it and also don't
but maybe I'll like it more, when I get to know it better.
thx for the answer anyway
for some reason... my first slash command is not registering
how do I enable logs or something so I can see what's going on?
it's happening on all of my bots
will the view deleted when the message was deleted
did you authorize the bot to create commands in a server
Also does anyone know if it's possible to make the bot ping a role using ctx.respond, I tried using AllowedMentions but it didn't work
modals, too
anyone here knows python well?
I have an issue with my terminal
I tried python manage.py makemigrations but its giving me errors stating No migrations to apply.
Can we have label with more than 45 characters in modals??
getting this error
In data.components.0.components.0.label: Must be 45 or fewer in length.
In data.components.1.components.0.label: Must be 45 or fewer in length.
In data.components.2.components.0.label: Must be 45 or fewer in length.
In data.components.3.components.0.label: Must be 45 or fewer in length.
api limitation
apparently not
i just need to get the server name
but ctx.guild.name is not working
error: Guild object has no attribute guild
That should work...
I have 2 options in a command, with both of them being autocompletes.
Can I influence the autocomplete of option 2, depending on the selected option 1?
So for example this:
Option 1 = A, that would make Option 2 autocomplete from [A, B, C]
Option 1 = B, that would make Option 2 autocomplete from [D, E, F]
@slash_command()
async def send_msg(
self,
ctx: ApplicationContext,
channel: Option(discord.TextChannel)
):
...
Im trying to take channel input as a TextChannel, it works on the discord side, but when i run the slash command , i get this error
you need the alpha/git version
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
@client.command()
async def guild_name(ctx):
await ctx.send(ctx.guild.name)
this should send the Server name
you should be able to
How would that work?
As from what I can see, you cannot access Option 1's variable, in Option 2.
Hmmmmmmmmm....
A name to value mapping of the options that the user has selected before this option.
so it would return {"Option 1 variable": "A"} I suppose then?
As that would work 🤔
Yea hope they fix it soon
anyone???
intents?
on
what intents are you giving your bot?
all are on
show me your code
doc is the guild object
How can I set default permissions (Permissions v2) for a slash command group?
it's the context
in an event there is no context object
on_guild_join only provides the Guild object it joined
oh
so do i just remove the doc???
youre trying to access the guild attribute of a Guild which doesnt exist
the argument name has no effect
Is there a limit on the number of items on a modal?
Yikes ok thanks
yep 5
pretty much everything related to UI components is in fives right now
5 buttons per row, 5 rows per view, 25 options per dropdown...
can anyone teach me how to provide an available file to the pillow package?
what are the max options u can pass in a slash command? and what are the max arguments u can put in one option
Thank you :)
I still get a error that 'APPLICATION_COMMAND_TOO_LARGE', 'message': 'Command exceeds maximum size (4000)
Is there a way to get lines from the logs in the console (where the prints go) and send it as a message
how to get a bot to create a new channel in a specific category?
i think there is a command like .create_category_channel
yeah. but keep getting errors for the category aspect
try .create_text_channel('name', category='category')
still getting errors
oh
oh?
'str' object has no attribute id
are u like extracting .id from a string?
can i see the code?
am pretty sure if u use the ip u use is without the ' '
if u wanna use the ' ' just straight up put the name of the category
getting the same error
go to line 1052
ohhh bruh
line 1160 you forgot to close ur ()
also i wanna see this line cuz it says str object has no attribute id so the problem might be there
its only 88 lines long atm
then why
let me debug this shit real quick
am a noobie but still lol
is that the full error?
yep
okay give me a moment
class AppealButtonsView(discord.ui.View):
def __init__(self, channel):
super().__init__()
self.channel = channel
@discord.ui.button(label="KMC", style=discord.ButtonStyle.secondary)
async def close_callback(self, button, interaction):
embed = discord.Embed(
title="**KMC Ban Appeal**",
description="Please put down the reason why you were banned from the KMC and why you feel you should be unbanned.",
color=discord.Colour.green()
)
await interaction.response.edit_message(view=self)
await self.channel.send(embed=embed)
await interaction.guild.create_text_channel(name='ticket', category=940628083592028230)
@discord.ui.button(label="Main Server", style=discord.ButtonStyle.secondary)
async def button_two_callback(self, button, interaction):
embed = discord.Embed(
title="**Main Server Ban Appeal**",
description="Please put down the reason why you were banned from the 104th and why you feel you should be unbanned.",
color=discord.Colour.green()
)
await self.channel.send(embed=embed)
@discord.ui.button(label="NTR", style=discord.ButtonStyle.secondary)
async def button_three_callback(self, button, interaction):
embed = discord.Embed(
title="**NTR Appeal**",
description="Please put down the qual you were NTRd from, reason why you were NTRd and why you feel you should be unNTRd.",
color=discord.Colour.green()
)
await self.channel.send(embed=embed)
@bot.command()
async def ticket_panel(ctx):
await ctx.message.delete()
channel = bot.get_channel(976499170879885312) # control pannel
button_channel = bot.get_channel(929759484593721386) #sends the embeds from the buttons
embed = discord.Embed(
title="**Appeals**",
description="Select an option for which type of appeal you need.",
color=0xf0f0f0
)
view = AppealButtonsView(button_channel)
await channel.send(embed=embed, view=view)
bot.run(TOKEN)
right
thats the code related to this
okay thx
Hey how i can with buttons open a modal?
i dont find a docs to this..
await interaction.response.send_modal
i believe it takes a Modal object that is to be sent to the user
@slender lintel
and yes it takes the Modal object that is to be sent to the user
and so how i can options in the modal? how give a number#
nope
so this with number is a example
only text fields
@commands.Cog.listener()
async def on_ready(self):
view = discord.ui.View(timeout=None)
role = self.bot.db.execute("SELECT * FROM Roles")
for row in role:
role = self.bot.get_guild(row[1]).get_role(row[0])
view.add_item(RoleButton(role))
self.bot.add_view(view)```
Ignoring exception in command reactionrole:
Traceback (most recent call last):
File "C:\Users\Ansh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 126, in wrapped
ret = await coro(arg)
File "C:\Users\Ansh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 856, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\Ansh\Desktop\Coding\Python\Discord stuff\button role\2\buttonrole.py", line 98, in reactionrole
await self.bot.db.execute(
AttributeError: 'Bot' object has no attribute 'db'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ansh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 993, in invoke_application_command await ctx.command.invoke(ctx)
File "C:\Users\Ansh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 357, in invoke
await injected(ctx)
File "C:\Users\Ansh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Bot' object has no attribute 'db'```
Ohh and how i can options ?
none
Why am i getting this error. Can someone help please. Thanks.
you have to sanitize/validate when the interaction comes through
does that mean nothing?
mhmm okay thanks despite it
did you set the db attribute of the object?
no
then set it
it worked ty
how would you make a ticket naming system(e.g. ticket -0001)?
i search a number (1799) when is not correct come a error but dont working..
if 1799 == None:
await interaction.response.send_message(f"Falscher Code!")
else:
await interaction.response.send_message(f"Geschafft! Du hast dich erfolgreich verifiziert!")
uh....
1799 == None is always gonna be false
and how is correct?
what are you trying to check
if the code is written correctly
any idea why this wont work?
you know also 1799 is the correct code when the user but 1029 type a error
still unsure what you're trying to do there
self.CloseButtonView() maybe? where did you define it
also it should be kticket.send, not kticket.id.send
Mhmm 1799 is a code (is the only correct code) so when but a user not 1799 typed come a error message yk?
should be uppercase discord.ui.View in the subclass
what variable is the code
So here
i have tryed with variable but not working
ahh i think you've misunderstood how it works
yeah maybe
so you're trying to check if they've entered 1799 in the modal
yes
you can get what they entered by accessing self.children[0].value
how do you subclass a button?
im talking about this
and how can i check this code?
but subclassing a button would be similar to a view
just check if self.children[0].value == "1799"
so?
yeah atm thats its own class
that should work
yeah, you did discord.ui.view instead of discord.ui.View
ive changed that
still not working?
nope
can you show the error
yeah its working but 1799 is the correct code.. not the not correct code
which is why you have the else, right?
Oh i have see it xD Im sry
all good
it wont run as its: "CloseBUttonView" is not defined
sorry
all good
can I also do this in a variable?
yep
so for example, since code is a list you can change it to if self.children[0].value in code
which would let you do multiple "correct" codes
so?
do you by any chance know how to make a ticket counter naming system
(e.g. ticket - 0001 , ticket - 0002)?
well you'd just have to save your counter to another file
Thank you! 
all good
tbh counter systems aren't really necessary either, you could just generate a random number and it'd have the same functionality
pycord also has the built in utility discord.utils.generate_snowflake() that'll generate a discord-style ID which is pretty likely to be completely unique
okie, thanks, does pycord have a readthedocs page?
thanks
also https://guide.pycord.dev/ for a more step-by-step resource
last question for to day why does update my modal not the code
don't quite understand the question
though if i had to guess, you need to restart the bot to update your callback
yeah but how can i fix this?
ehhhh
it's hard to figure out because discord is pretty weird when it comes to syncing callbacks
mmhmm is that not working a random number to generate?
How can I get the full command that got called by the user? I'm speaking of a slash command of course.
Wdym
ctx.command.qualified_name is the best you can get without any extra work
if you want the full command including options, what the user entered etc, you should experiment with ctx.interaction.data["options"]
since that will include everything
yep that's what I want, thx
how do you delete a channel after a delay
await asyncio.sleep(seconds) if you want the command to stall for a bit
delete_after= param in .send or msg.delete() after you did what you want
note if it's via a slash command or other interaction and it's lasting more than 3 seconds you should defer
Ignoring exception in view <CloseButtonView timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Close' emoji=<PartialEmoji animated=False name='🔒' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 365, in _scheduled_task
await item.callback(interaction)
File "c:\Users\philc\Desktop\ticket bot WIP\ticket bot.py", line 35, in close_callback
await self.channel.delete
TypeError: object method can't be used in 'await' expression
Do command checks like guild_only or is_owner also work with slash commands or only with the prefixed commands?
It work with both
perfect
Is there somewhere a good guide on what to change when switching to slash commands?
That's not really what I need
you dont really have to change so much stuff
Do I have to change more other that using ctx.respond and discord.slash_command?
you dont need to use aliases from the prefix commands, only if you would use bridge commands
Concept
no, quite literally await asyncio.sleep()
it's a separate function that waits for the amount of seconds you specify
then you can delete after that line
delete()
it works but im getting an error:
Ignoring exception in view <CloseButtonView timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Close' emoji=<PartialEmoji animated=False name='🔒' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 367, in scheduled_task
await interaction.response.defer()
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 471, in defer
await adapter.create_interaction_response(
File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\webhook\async.py", line 192, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
I don't need to or I can't?
Do aliases not work with slash commands?
ah you need to respond to the interaction
how is this callback triggered?
button
you can add them but they wouldn´t work, with a bridge command it would work
i recommend either:
- replace the
self.channel.sendwithawait interaction.response.send_message - leave the
self.channel.send, but at the start of the callback, you do something likeawait interaction.response.send_message("Deleting ticket...")
ok so if I would really want to have an alias for a slash command I would have to register the same command again but with a different name?
thank you so much
all good
kind of... but this isn't really recommended
How do I register a slash command that works in dm's too?
discord treats them as completely different commands
which will cause issues with permissions and such
generally slash commands don't need aliases because you can just search for the command you need
has to be a global command; no guild_ids allowed
oh ok, makes sense
and how would I make a global slash command that won't show up in a dm?
add the discord.guild_only decorator... i think?
@discord.guild_only()
i think this might be broken in rc1 though
though there's a pr you can apply if you want it working
No, it's not that urgent, just wanted to know
fair enough
Can I do command checks on command groups? Like defining a whole command group as guild_only instead of doing it for every command in this group.
It got merged
whats the cmd for pycord rc ?
py-cord==2.0.0rc1
oh
Hi guys, how do I get the ID of the user who sends a command?
i think
?rtfm id
?rtm
?rtm ID

do something like
user.default = ctx.author.id
Like if var2 != true, user = ctx.author.id?
@south ermine
Okok thank you!! im gonna try it
I have this. And it still wont wokr :I
that img is my issue
I think this will work @glad saffron
Wait, I dont understand what you mean by that
Also I'm sorry but I dont think I'll be able to help you with your issue I am really new to Pycord
def foo(ctx ,user : Option(str, description=bar):
this
user now has an attribute called default
correct ?
Where would the user.default = ctx.author.id be in this function?
Within the function where user is instantiated
You have a param called user
You can do
foo(ctx, member: discord.Member = None)
And then member = member or ctx.author
they want the id to be the default
Okok I think I should explain what I want the thingy to look like
now under the function definition set the users default attribute to the ctx.author.id
I want there to be an optional thing you can respond with but if you dont do the optional thing, then your ID would be the default but if you answer it then the person you put id's would be the default
Okok ill try that
would this work?
wait dont have a default inside the Option
okok
Its still set to required
Maybe I should reinvite the bot to see if its just a bug with discord?
Also I tried running it and it gave me this 😅 discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'default'
try adding this back maybe
Ughhhhhh
Ok this code it works
But it's still set as a required option
I'm gonna reinvite the bot to see if its just a bug with discord
IT WAS
YAYYYY
its now optional
😭
thank you for the help!!
Hopefully your problem gets resolved too
Also just out of curiosity, why does your cmd look like that/
i knew what i was trying worked lol
its terminal based editor
Ah
editing directly in the vps
it says ubuntu, but youre on windows?
Also your bio has these date thingies how do you do that?
unix timestamp
i see
@bot.slash_command(name='statuscheck', guild_ids=slash_guilds)
async def statuscheck(ctx):
await ctx.respond(ctx.author.status)```
For some reason, this always returns offline no matter what my status is, any ideas?
yeah, known bug, fixed in ##1365 but it needs testing before merge into master
current workaround is to do ctx.guild.get_member(ctx.author)
Oh thanks, how can I download the py-cord with the fixed version?
its not currently in pycord's master branch so you'd have to clone the branch that i have it on
should be merged soon if you just wanna use the workaround for now
Alright yeah ill just use the workaround for now
pip install py-cord2.0.0==rc1
ty :D
fix isnt in rc1 lmao
okay so i looked back at your message and turns out its only with application commands
so i can use it in on_message
yeah, interactions/options are where it occurs, fairly certain it functions fine with prefixed-esque stuff
oh thats even better, saves me a lot of trouble, thanks :D
i just gave an install command for a stable version of pycord so
¯_(ツ)_/¯
all good
Hi guys, how do I have a bot send a message in a specific channel?
I have the ID of that channel but I'm not too sure on how to have it send the message to it
Yes?
You can see it in the thread thing i made
await ctx.bot.get_channel(channelid).send()
b!rtfm pyc get_channel
discord.Bot.get_channel
discord.Client.get_channel
discord.ext.commands.Bot.get_channel
discord.Bot.get_all_channels
discord.Client.get_all_channels
discord.ext.commands.Bot.get_all_channels
discord.Guild.get_channel
discord.Guild.get_channel_or_thread
discord.Guild.text_channels
discord.Guild.fetch_channel
thankyou 😁
@tasks.loop(minutes=1)
async def set_rate(bot:discord.Bot):
global dbu
by=randint(4,9)
inc=choice([True, False])
ch=bot.get_channel(ECRCH)
msg=await ch.fetch_message(ECRMG)
names=["ich","wsi","soc","gzi","fsp"]
cp=[]
np=[]
for i in names:
cur=await dbu.execute("SELECT vale FROM market WHERE cname=?",(i,))
res=await cur.fetchone()
cp.append(res[0])
day=datetime.utcnow().strftime("%A")
strs=f"Day: {day}, Note: Markets are closed on Sunday"
if day=="Sunday":
strs=F"It's {day}, The markets are closed today "
np=cp
else:
if inc is True:
for i in cp:
i+=by
np.append(i)
else:
for i in cp:
i-=by
np.append(i)
v=0
for j in names:
await dbu.execute("UPDATE market SET vale=? WHERE cname=?",(j,np[v]))
# print((j,np[v]))
await dbu.commit()
v+=1
em=discord.Embed(
title="Comapny Value List:",
color=discord.Color.random()
).add_field(
name="🍒 iCherry",
value=f"{np[0]}"
).add_field(
name="🌿 William Inc.",
value=f"{np[1]}"
).add_field(
name="🦾 Socialize",
value=f"{np[2]}"
).add_field(
name="🎮 Gamezionic",
value=f"{np[3]}"
).add_field(
name="🥾 Footworks Inc.",
value=f"{np[4]}"
).set_footer(
text=strs
)
await msg.edit(content=None,embed=em)
my code, it's not updating db,there's a problem in the for loop part.. everything else works fine
Does any1 know why ctx.content does not display anything?
import discord, urllib.parse, asyncio, random, json
from discord.ext.commands import bot
from discord.ext import commands
from discord.ui import Button, View
from collections import defaultdict
# we will then need to connect our discord account to the discord bot through
# https://discord.com/developers/applications
token = open('token.txt', 'r').read()
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
# on bot startup
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game('random message'))
print(f'{client.user} has connected to Discord!')
# on bot message
@client.event
async def on_message(ctx):
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name} {ctx.author.id}: {ctx.content}")
print(ctx.guild)
msg = str(ctx.content)
print('Message Sent:', msg)import discord, urllib.parse, asyncio, random, json
from discord.ext.commands import bot
from discord.ext import commands
from discord.ui import Button, View
from collections import defaultdict
# we will then need to connect our discord account to the discord bot through
# https://discord.com/developers/applications
token = open('token.txt', 'r').read()
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
# on bot startup
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game('random message'))
print(f'{client.user} has connected to Discord!')
# on bot message
@client.event
async def on_message(ctx):
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name} {ctx.author.id}: {ctx.content}")
print(ctx.guild)
msg = str(ctx.content)
print('Message Sent:', msg)
No error?
though i am not good at sql, everything else looks fine to me.
nope
The on_message is an event not a command so your message content is stored within the ctx argument you've passed in. I would recommend u to change ctx to message cuz it's more readable like that
Also pls don't send your whole bots code just send what's not working
ok thank you 🙏 sorry to ask, but what would i need to specify in
this part or write instead of ctx.content to be able to retrieve message contents?
@client.event
async def on_message(ctx):
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name} {ctx.author.id}: {ctx.content}")
@client.event
async def on_message(message):
print(f"{message.channel}: {message.author}: {ctx.author.name} {message.author.id}: {message}")
The message content is already stored inside the argument you don't need to access it again
no, idts
accessing the content attribute of Message requires you have the message_content intent enabled and provided to your bot
?tag 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)
Hi guys . As my project ad skipper I want to put multiprocessing in my code using Pipes I want to communicate between processes. I don't really have any idea what I am doing. This is part of my final requirements in school. Our teacher never teach us about, multiprocessing, multithreading, parallel and etc. And he want us to put multiprocessing, multithreading, parallel and etc. in our code. My question is am I doing it right? or I am just messing around in my code? Skip add doesn't print in the system when the ad is skipped. it says that Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
how can i make a photo that can be opened in pillow package?
Hey how i can Update a Modal?
Why can't I import CommandPermission from discord.commands? I'm using rc1, is that the problem?
how would you get a bot to read from a json file?
permissions v1 is deprecated and support removed from rc1 onward
so what can I use instead?
how can I use them with command groups? Both the checks and the permissions v2.
How do I get the value stored in a specific grid in MySQL???
I just started learning abt it so don;t know much
Also, is there a way to get an audio file from audio
the checks you use with the respective commands you want to restrict and permissions v2 i have no idea. havent delved into them myself yet
is it possible to create a file for a command and add it to the main bot file?
So just with a decorator before the declaration of the group?
i guess
how do i add choices to option when i fetch the data from the database with a specific user?
or no way?
do you mean dynamic slash command option choices?
example?
is that what you mean?
not sure what u mean so i would like u to explain 🙂
youre saying something about pulling info off a database and then providing them as choices to the user
yeah
?tag ex
Bot examples: https://github.com/Pycord-Development/pycord/tree/master/examples
Slash command/context menu examples: https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands
Buttons, dropdowns example: https://github.com/Pycord-Development/pycord/tree/master/examples/views
slash command, autocomplete example
possible to fetch something that the user chose a user
uh
how do i explain
like
/find <member> <thing>
yes
so it only provide what the member has as a <thing>
ok
and for the love of god actually read the docs for the applicable context object
youll find what you need there
ok
I installed this package for 10 times and I still got the same error?
Traceback (most recent call last):
File "main.py", line 96, in <module>
@bot.slash_command(name="ping", description = "Check the time i take to reply to you!")
AttributeError: 'Bot' object has no attribute 'slash_command'
pip install -U discord-py-slash-command
dont use it with pycord
which package should I install?
pycord 2.0 supports slash commands
its installing discord.py
discord-py-slash-command requires discord. Uninstall that and discord.py
installed this again; pip install git+https://github.com/Pycord-Development/pycord
now it worked thx
Use cog
when updating a channel's permissions.
whats the global permmision(@ everyone)?
Guild.default_role
Simple question this time: How do I remove a view from a message? Setting view=None raises this error:
return await self.followup.send(*args, **kwargs) # self.send_followup
File "/opt/homebrew/lib/python3.10/site-packages/discord/webhook/async_.py", line 1561, in send
if view is not MISSING and not view.is_finished():
AttributeError: 'NoneType' object has no attribute 'is_finished'
The documentation for WebhookMessage says "The updated view to update this message with. If None is passed then the view is removed."
Ditto the documentation for Message.edit()
Actually, I think my problem is different. This occurs when sending a message with view=None
python3 -m pip install py-cord
when typing that I only get this:
..
In a channel, i want to get the id of the first message only, any ideas on how?
eh...
the best you can do is use channel.history with an "infinite" (or very large) limit and then get the last/first item, depending on your implementation
i recommend reading https://docs.pycord.dev/en/master/api.html#discord.TextChannel.history for a better idea on doing so
Theres a param which is oldest_first but issue im facing is when i do
messages = await channel.history(limit=2, oldest_first=True).flatten()
print(messages)
print(type(messages))
msg = bot.get_message(977238207659909126)
print(msg)```
My last print(msg) is none and print(messages) gives me
```[<Message id=977238207659909126 channel=<TextChannel id=976338556559691876 name='test' position=14 nsfw=False news=False category_id=971116553032585226> type=<MessageType.application_command: 20> author=<Member id=971276352147845190 name='Powered Bot' discriminator='6049' bot=True nick=None guild=<Guild id=971110220568879134 name='Powered Bots' shard_id=0 chunked=True member_count=11>> flags=<MessageFlags value=0>>, <Message id=977238208209362984 channel=<TextChannel id=976338556559691876 name='test' position=14 nsfw=False news=False category_id=971116553032585226> type=<MessageType.default: 0> author=<Member id=971276352147845190 name='Powered Bot' discriminator='6049' bot=True nick=None guild=<Guild id=971110220568879134 name='Powered Bots' shard_id=0 chunked=True member_count=11>> flags=<MessageFlags value=0>>]
because get_message reads from a different cache
oh hm, well what should i be doing then>
are you sure 977238207659909126 is in that channel?
according to that print, it is
oh alrighty lemme try that
well i want to be able to edit that message later too
which is why im going thru all this trouble
well yeah you have the object
so you just work on that
note that the more messages in a channel, the more expensive it becomes to use history; it can take a while before returning anything
makes sense
oh wait
i just realised your way of doing it works way better than what i initially suggested
limit=1, oldest_first=True will instantly return the first message
all good, if anything your test code above was how i found out lol
guys I Need help with attachments in slash commands
@bot.command(description="Post on your profile")
async def post(ctx, image : discord.SlashCommandOptionType.attachment):
link = image.url()
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cur:
await cur.execute("INSERT INTO posts (user_id,image_link) VALUES (?,?)",(ctx.author.id,link))
await db.commit()
embed = discord.Embed(title="Successfully Posted :")
embed.set_image(link)
discord.SlashCommandOptionType doesnt seem to work
it raises this error :
File "D:\Tomm's Bot Stuff\Instacord\bot.py", line 53, in <module>
async def post(ctx, image : discord.SlashCommandOptionType.attachment):
File "C:\Users\My PC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\bot.py", line 813, in decorator
result = command(**kwargs)(func)
File "C:\Users\My PC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\commands\core.py", line 1580, in decorator
return cls(func, **attrs)
File "C:\Users\My PC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\commands\core.py", line 644, in __init__
self.options: List[Option] = self._parse_options(params)
File "C:\Users\My PC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\commands\core.py", line 691, in _parse_options
option = Option(option)
File "C:\Users\My PC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\commands\options.py", line 177, in __init__
elif issubclass(self._raw_type, Enum) and (doc := inspect.getdoc(self._raw_type)) is not None:
TypeError: issubclass() arg 1 must be a class```
Ive reinstalled thrice
just do discord.Attachment
i can't recall any scenario in which you need SlashCommandOptionType at the moment, the regular classes work just fine
guide.pycord.dev recommends discord.SlashCommandOptionType
but ok
ah haven't read the guide much
File "D:\Tomm's Bot Stuff\Instacord\bot.py", line 53, in <module>
async def post(ctx, image : discord.attachment):
AttributeError: module 'discord' has no attribute 'attachment'```
clearly in pip list
why
sorry
Capital A
is there a fix for this?
Use interaction.guild?
Im not sure if this works
seems to work
do you know how to add roles to the overwrites?
How Do i make a for loop in slash autocomplete?
For what?
You can just use a list?
but it should display the guilds of a user
Oh
Does anyone have a code example of using image inputs in a slash command? There's not one in the Guide (yet)
(nm, found it in the main repo - https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py)
how would you make an incrementor for a ticket system?
(format: 0001, 0002 etc.
0017, 1732)
is there a way to have more the 25 options in slash commands?
i cant edit the ctx.response messages, i keep getting thrown an error like this : 'Interaction' object has no attribute 'edit_message'
i have tried using the normal message.edit and it gave the same error
can .respond() with ephemeral on_message messages?
nope
so would await edit_original_message(embed=new_embed) work? or is edit_original_message meant to be something else?
ctx.respond doesn't return a Message, it returns an Interaction
so with your naming, you do message.edit_original_message... because message in this case is an Interaction
and message is my ctx.respond variable name?
well that's what im guessing anyway
ight ill test it out, thanks
@crimson coral do you know how to make the bot think?
is it await ctx.deffer() or something
yea, it allows the bot longer to send a message
yes await ctx.defer() is used when you know the bot will take more than 3 seconds to respond
so I have a command which calls this and after it makes the dataentry the command doesn't do anything else and just stops after making the dataentry when I use the command once again cause there already is a dataentry it doesn't create one and the command words, anybody know what's happening here?
this did work too, cheers 
nice
I answered you in your thread #977232172626898986
Hey, when i restart the bot then is my button not working, i have tried with on_ready but not working..
@commands.Cog.listener()
async def on_ready(self):
view = discord.ui.View(timeout=None)
view.add_item(teststation_button())
I can't view the slash command
using the latest beta version^^
bot remove from the server and new add the bot to your server
reinvite the bot?
yes
Here's the persistent example.
@slender lintel refer to this, you're mainly missing the self.bot.add_view but it's a good read anyway
so only self.bot.add_view more not?
or + this?
self.bot.add_view(view) along with your previous code
but again, you should have a general look at the example
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\[Teststation].py", line 79, in on_ready
self.bot.add_view(view)
AttributeError: 'teststation' object has no attribute 'bot'
client?
where did you define the on_ready
in my cog
and your cog doesn't have a bot attribute...?
huh? indeed
can you show your cog's __init__
now this command is back
not __init__ i have only class teststation(commands.Cog):
need init?
read https://guide.pycord.dev/extensions/commands/cogs for how to properly implement cogs
does it show in the server's Integrations tab?
so this is correct?
class teststation(commands.Cog):
def __init__(self):
self.bot = bot
def __init__(self, bot):
no, only ping
can you show the code for the slash command
dont working my button is by restart not working
@slash_command(name="play", description="Plays a music!", guild_ids=guild_ids)
async def play(self, ctx, *, query):
player = self.bot.lavalink.player_manager.get(ctx.guild.id)
query = query.strip('<>')
if not url_rx.match(query):
query = f'ytmsearch:{query}'
results = await player.node.get_tracks(query)
the starting
using cog btw ^^^
when are you loading the cog
can you show the updated code
(also please consider making a help thread via #969574202413838426)
last
def setup(bot):
bot.add_cog(Music(bot))
Oh i haved thanks
in the main file?
yes
not in on_ready or anything right?
yeah
hm
did you override on_connect?
channel.id does get the channels id right?
yeah
