#General Help
1 messages · Page 13 of 1
yo how can i add cooldown to command
so i already have this
@commands.cooldown(1, 15, commands.BucketType.user)
and this
@bot.listen()
async def on_command_eror(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embedvar = discord.Embed(
description = "That command is on cooldown, try again in " + str(error.retry_after),
color = discord.Color.red()
)
await ctx.respond(embed=embedvar, ephemeral=True)
but i get this error
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 13.50s
its not even an error
its correct
but instead of sending it in the server it sends it in the console
i am running two programs with same token everything works fine except slash commands
lets say the first program have slash commands and the 2nd one only have text commands(no slash commands)
whenever i use slash command from bot all the commands disappears after that
for instance when i define slash commands in second program they don't appear until the first program's any one slash command is called and when we call then all commands from first program disappears and it only shows second program's slash commands
idk but i did this in a different way you can try
but its in cog
what isi t
@commands.command()
@commands.cooldown(x,y,z)
async def your_command(self, ctx):
your stuff
@commandname.error
async def local_handler(self, ctx, error):
await ctx.send(str(error))
this
Application command error have their on event
so it should be bot.event or what
Yes, it should be on_app_cmd error or something
Ooh
or i have bridge command
this should work fine
I suggest you listen to both commands error and the appplication command error
why u got self?
This is rough, youll have to set the error handler 1 by 1 for every command
cuz its in cog
tf is cog
well cogs are type of containers in your code for specific functionalities you can define different cogs
they will keep the code well maintained
ok try adding this below your command
@commandname.error
async def local_handler(ctx, error):
await ctx.send(str(error))
AttributeError: 'BridgeCommand' object has no attribute 'error'
dont think .error works with bride commands but it works with slash commands?
thats weird
yeah
Try adding on_app_cmd_error aswell
b!rtfm pyc on_application_command_error
throws same error
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 13.03s

"this only fires id toy do not sepcify any listeners for command error"?
@bot.event
async def on_command_eror(ctx, error):
await print("lol")
@bot.bridge_command(name = 'work')
@commands.cooldown(1, 15, commands.BucketType.user)
async def workcmd(ctx):
await work.work(ctx)
where work is a coroutine function i defined elsewhere
what i think happens is that the bot recongizes that a command has been run on cooldown and therefore throws an exception
however for some reason the on_command_error function doesn't recognize that
and therefore doesn't respond
ok
i might just have to resort to putting a if loop in every command
b!rtfm pyc permission
discord.PermissionOverwrite
discord.PermissionOverwrite.from_pair
discord.PermissionOverwrite.is_empty
discord.PermissionOverwrite.pair
discord.PermissionOverwrite.update
discord.Permissions
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
b!rtfm pyc channel
anyone know how to check if user has a certain permission in a channel?
b!rtfm pyc channnel permission
No results found when searching for channnel permission in pyc
b!rtfm pyc channel_permission
can bot(verified) go off when it gets overloaded due to any heavy task or traffic
Can’t you just use @has_permissions(whatever)
not in the way im using it, im trying to see if a user has the view_channel permission in a list of channels in the guild
i cant seem to get the bot to check the users channel permissions
reading the docs rn but cant see much on my issue
You need rc1
uninstall the old version and use
pip install py-cord==2.0.0rc1
Did that, still didn't work, am I supposed to do pip install discord.py
so what now
But if there’s supposedly no discord module installed just install discord with pip install discord
Or uninstall and reinstall it
done, but still didn't work
Microsoft Visual Studio
Make sure the one being used by ide is same as the one running on your system
how can I check that
You mac?
windows
Alright just google how to check Python version console windows
Yh check what your system is using
k
I’ve had module errors where it’s bc system and ide use different versions
the python version on the pc is 3.10.4
hm
any idea how to change the python version in vs
No but just google it
Here it shows that I have these versions
but when i use python --version in the cmd it says version 10
how can I change it from 10 to 8
or to 9
hello
How can I make options in my slash command?
it should show me a predefined options when invoking slash command
like this
Can I ping helpers?
Check if this helps
In this video we discussed about the predicament of switching to slash commands and talked about ways to create subcommands, all Option params and error handling with cooldowns and permissions.
Install pycord master branch:-
pip install git+https://github.com/Pycord-Development/pycord
Join my Discord Server:-
https://discord.gg/cRGWDtu3W8
P...
I just watched it
it doesn't show these
idk then
@sharp summit do you mean predefined options as in you can choose from a list of values for an option?
I want to get a message from on_message event and I want to know which message it was replying to. How do I get it?
I don't know myself but try googling about setting windows default py
b!rtfm pyc message.reference
how to add cooldown on bridge commands
I couldn't find a documentation with the name commands.cooldown! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc commands.cooldown
discord.ext.commands.Cooldown
discord.ext.commands.Cooldown.copy
discord.ext.commands.Cooldown.get_retry_after
discord.ext.commands.Cooldown.get_tokens
discord.ext.commands.Cooldown.per
discord.ext.commands.Cooldown.rate
discord.ext.commands.Cooldown.reset
discord.ext.commands.Cooldown.update_rate_limit
discord.ext.commands.cooldown
discord.ext.commands.cooldowns.Cooldown
@lucid cove try looking into the above
i think for prefix you kinda need to create one manually idk
well im using bridge
and the normal app / slash command setup doesnt work with bridge
Done that thanks
How can I reply so that the person who wrote the slash can only see it. In the same message as the error?
Make sure you are using ctx.reply and not ctx.send
ohhh,
ephemeral=True
np
Hi, I'm trying to find the amount of Scheduled Events that's been created by a specific member. My approach is by iterating through each Scheduled Event in the guild and checking the event creator. However, for some (but not all), the event creator is None when it is not. I have enabled all Intents
ah thx
is it possible to use n args with slash commands?
@bot.slash_command()
async def list(ctx, *args):
mylist = ', '.join(args)
await ctx.send(users)
if not possible can i use bridge since it allows for ext.commands capabilities or will i have to use commands
Why would you use *args. Just use args.
i want to be able to put in as many inputs as i want
String options aren't 1 word.
wym
Slash commands options are not like normal commands.
ah, ok
Hello I need some help
I want to use task.loop but in cog :)
how can I do that?
cause to start the loop we need to use func.start() right? where should I use it then?
@here
#1, that doesn't work
#2, it's not that important
#3, docs tell you how to do that
: (
I read the docs bro.. I can't get it how to use it in cogs
I read that bro
my func does not run without func.start()
and with the func.start() inside init it says func not defined :) \

it's not a function. It's a method
yeah :)
ofc it's not defined. You need to use self.method.start()
How can i make that only author can use a button?
You can make the message ephemeral or add author into the constructor for you view or create an instance of button instead of sub-classing it
quick question: Is it not possible to have further arguments in a subcommand of a group?
The arguments are not showing up on Discord
there is a limit of 25 options. a subcommand and a command group each take one option
25 per group or per bot?
The only way around this is enabling the presence intent and using await bot.fetch_user(id)
per command
Sometimes if you try and use the command, the command will update
so far it always updated instantaneously, since i have it running only on my guild 
@wrdl.command(name="start", description="Start Wordle")
async def wordle_start(ctx: commands.Context, k: Option(int, name="length", description="Input a word length from 3 to 8. Default is 5", min_value=3, max_value=8, default=4)):...```
It's not showing the option length 😩
well, why is the ctx commands.Context?
uh idk, I have it always like that and it always works
I only added it so that vs code has the auto complete for ctx which it otherwise doesn't have...
but lemme see if removing it helps
yea, no change :(
the commands works as normal, just that it doesn't show any option to input length
so it's always the default value that i have in the Option
Well, sometimes this works for me, but I unregister and re-register the command
oh alright, lemme try that
Damn, that actually worked 😃 thanks so much
hi
role = guildx.get_role(982715970890117170)
user = interaction.user
await user.add_roles(role)
how can i fetch a user id like when you press this button in direct messages from the bot you will get the role in guildx server
well, you have interaction.guild
uhmm where does i have it
@discord.ui.button(label="", style=discord.ButtonStyle.primary, emoji="➡️") # Create a button with the label "😎 Click me!" with color Blurple
async def button_callback(self, button, interaction):
# Figure out who clicked the button.
# Get the role this button is for (stored in the custom ID).
guildx = bot.get_guild(869210320856563723)
role = guildx.get_role(982715970890117170)
user = interaction.user
#role2 = interaction.guild.get_role(tagrole)
button.disabled = True
button.label = "Verified"
await user.add_roles(role)
embedVar = discord.Embed(description=f'You re verified. Welcome!', color=0x00ff00)
await interaction.response.edit_message(embed=embedVar, view=self)
time.sleep(10)
await interaction.channel.purge(limit=2)
#View.delete()
pr 1365 also fixes it but it isnt merged yet
for some reason slash commands just wont work
like
it shows as registered
but says it didnt respond
ususlly i just have to wait 5mins but its been doing it for the past 30mins
even with a really basic command it doesnt work
@bot.slash_command(guild_ids=[settings().guildid])
async def hello(ctx):
await ctx.send("Hello!")
doesnt work
ctx.respond
change .send to .respond I think
@slender lintel
yeah
no i mean
it litearlly
does nothing
even when i add a print statement
use ctx.respond
ok
one sec
still nothing
use it on another channel
alright
didnt work
it quite literally does nothing
await ctx.respond("hello!")
even if i put a print statement it doesnt print
its like this?
@bot.slash_command(guild_ids=[settings().guildid])
async def hello(ctx):
await ctx.respond("Hello!")
yes
try to reinvite the bot
alright
did you give it the application.commands scope when inviting
yes
if i didnt it wouldnt register
this is registeriang
not showing errors
quite literally doing nothing
it wont even print when i add a print statment
sec
intents = discord.Intents.all()
bot = commands.Bot(prefix=">", intents=intents)
class settings():
token = "token"
guildid = 1
@bot.slash_command(guild_ids=[settings().guildid])
async def hello(ctx):
await ctx.respond("Hello!")
bot.run(settings().token)
how do i fetch the invite of another bot
well you don't really need to, the general format is
https://discordapp.com/oauth2/authorize?client_id=BOT_USER_ID&scope=applications.commands+bot
async def perms(ctx, member: discord.Member):
if ctx.author.guild_permissions.administrator:
await member.guild_permissions(ctx)
await ctx.respond(ctx)
``` What am i doing wrong here? I am trying to see the permissions of the member given in the command
ty
how do i escape "get" since my command name will be "get-invite" so I have
…
async def get-invite(self, ctx)
…
and it’s marking "get" as a func?
I see these quite a lot, what does the asterisk mean? Do I need to substitute any arguments in it?
its still doing it
ik with discord.utils get is a function but cld just use dif name like 'generate-inite'
so there isn’t a way of me using get-invite?
think it means you can pass a changing number of arguments so it cld be 1 or 10 arguments
ygm
there are probably bypasses but dk off top of my head, try google
i think so, ty
i tried searching it up b4 I came here but no luck
b!rtfm pyc guild
b!rtfm pyc emoji
e
command names can only contain letters, numbers and underscores
(aka. word characters by regex standards)
oh i thought you meant slash commands, my mistake
but yeah for regular commands you can just specify name=... in the decorator
I’m using cogs
that shouldn't change anything?
so I’d have
@commands.command(name=get-invite)
?
e.g. if your command right now is like py @commands.command() async def get_invite(self, ctx...) you can do this instead py @commands.command(name="get-invite") async def get_invite(self, ctx...)
gotcha ty
it works, thankyou very much :)
How do I always return the ID of a user?
- For example, if someone runs
!ID @chaze, it will return the mentioned user’s ID. If another person uses!ID chaze (using username), it will return the ID of the username (in the provided guild). And lastly, if someone just uses!ID 831118106876969021 (my ID)it’ll just return that back?
Referring to this suggestion: #suggestions message
Embeds can have multiple images? Like where you set
embed.set_image()?
How would i take a Discord.Attachment and treat it like an image stored locally?
like lets say i have something like
text = OCR('./image.png')
would there be a way to just use the Discord.Attachment or do i need to download, use it then delete?
ImportError: cannot import name 'PartialMessageable' from 'discord.channel
i keep getting this even tho the code just worked
did somthing change
like 3 weeks ago
Did you update your py-cord?
b!rtfm pyc PartialMessageable
discord.PartialMessageable
discord.PartialMessageable.can_send
discord.PartialMessageable.fetch_message
discord.PartialMessageable.get_partial_message
discord.PartialMessageable.history
discord.PartialMessageable.id
discord.PartialMessageable.pins
discord.PartialMessageable.send
discord.PartialMessageable.trigger_typing
discord.PartialMessageable.type
idrk i used a reqs.txt
pretty sure u dont need to use import for that
check to see what version you're using
i cant print it cuz it runs error on import discord
and before that its not defined
using discord.__version__
- run "python -m pip list" and show me what version discord says
- copy and paste your import for PartialMessageable
py-cord 2.0.0rc1
im not importing that
it in module
i see
can you try this first?
uninstall py-cord and discord.py if its there
then install py-cord again and see if it fixes the issue
What does :< mean in F strings?
I found it here in discord.ext.commands.DefaultHelpCommand:
entry = f'{self.indent * " "}{name:<{width}} {command.short_doc}'
it's an f-string.
name = "John"
print(f"My name is {name}!") #My name is John!
@slow dome Yeah ik its an f string but what does the :< notation mean?
I believe it makes the string right aligned?
Oh ok thanks
how to do embeds?
at the moment yeah, just text fields
select menus coming soon once discord officially supports them
ok
how do i mention a
user
just
{member} ?
and how do i ban
oh wait nvm
Read the documentation.
@client.slash_command(name="multi", description="Multiples two numbers!")
async def ban(self, ctx,member):
embed=discord.Embed(title="Ban Successful ✅", description="Successfully Banned", color=discord.Color.red())
await discord.Member.ban()
await ctx.respond(embed)
so i have
is this ok?
hold up
When responding and sending an embed you need the embed keyword.
ok
but where do i put that
await ctx.respond?
I said when responding, so yes
yay
cant wait for it
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/runner/Embeds/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Embeds/venv/lib/python3.8/site-packages/discord/bot.py", line 1147, in on_connect
await self.sync_commands()
File "/home/runner/Embeds/venv/lib/python3.8/site-packages/discord/bot.py", line 770, in sync_commands
await self._bot.http.bulk_upsert_command_permissions(self._bot.user.id, guild_id, guild_cmd_perms)
File "/home/runner/Embeds/venv/lib/python3.8/site-packages/discord/http.py", line 359, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
update
why everytime i run the bot this show up on console and the commands disapear
rc1 pls
wut
update pycord to 2.0.0rc1
in ctx.respond
ctx.respond(embed=em)
lmao all good
docs? or guide?
i have a hard time reading api docs
if you'd prefer examples the repository has a good bit of examples to work off of
np
dope dude it works thx again
and you know how i can check perms?
@gilded widget
A decorator that limits the usage of a slash command to members with certain
permissions.
The permissions passed in must be exactly like the properties shown under
:class:`.discord.Permissions`.
.. note::
These permissions can be updated by server administrators per-guild. As such, these are only "defaults", as the
name suggests. If you want to make sure that a user **always** has the specified permissions regardless, you
should use an internal check such as :func:`~.ext.commands.has_permissions`.
Parameters
------------
perms
An argument list of permissions to check for.
Example
---------
.. code-block:: python3
from discord import default_permissions
@bot.slash_command()
@default_permissions(manage_messages=True)
async def test(ctx):
await ctx.respond('You can manage messages.')```
discord.default_permissions
embed=discord.Embed(title=self.children[0].value, description=self.children[1].value, color=2f3136)
embed.set_image(url=self.children[3].value)
embed.set_footer(text=self.children[2].value)
bruh
how to set custom color for embeds using hex code
it does not work
im testing it out
not sure how to do hex but you can do discord.Color.from_rgb(r,g,b)
how do see who banned a user
it worked btw
like user banned user
rgb?
nice
i used to make it with hex code when i was discord.py user
@gilded widget
how can i make a slash group?
i think you cant
from discord.commands import SlashCommandGroup
your_group = SlashCommandGroup("group_name", "group description")
@your_group.command()
async def test(ctx):
...
np
Yes, see the shared picture
and in cogs?
same
ok
to
yo
I am getting an error
Application Command raised an exception: AttributeError: module 'utils' has no attribute 'nitroButtons'
utils is a folder
And it has buttons.py in it
there is no method or attribute for this, at least in pycord
and I have multiple buttons in it
so
i used
import utils
and it wont do the command
permission = SlashCommandGroup("permission")
@permission.command(description="Get the profile picture of a user > Skyler")
async def admin(self, ctx, role:discord.Role):```
what is wrong
is there a traceback?
tested myself, no error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: '>=' not supported between instances of 'str' and 'int'
import discord
from discord.ext import commands
from discord.commands import SlashCommand
from discord import default_permissions
client = commands.Bot()
class clear(commands.Cog):
def __init__(self, client):
self.client = client
@client.slash_command(name="clear", description="clears a specified amount of messages")
@default_permissions(manage_messages=True)
async def ban(self, ctx, amount = None):
if amount == None:
embed=discord.Embed(title="Clear Failed ❌", description="Please specifie how many messages you would like to delete ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
else:
if amount >= 1000:
embed=discord.Embed(title="Clear Failed ❌", description="Do not go over 1000, /purge for 1000+ messages ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
return
if amount <= 0:
embed=discord.Embed(title="Clear Failed ❌", description="I cannot delete zero messages ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
await ctx.guild.clear(amount)
em = discord.Embed(title="Cleard messages Successfully ✅", color=discord.Color.dark_gold())
em.add_field(name="cleard amount", value=f"{amount}")
await ctx.respond(embed=em)
def setup(client):
client.add_cog(clear(client))
heres source code
idk
[Skyler]: [ COMMANDS ] >>> Error Command: permissions.py
import discord
import sqlite3
from discord.ext import commands
from discord.commands import slash_command, SlashCommandGroup
class perm(commands.Cog):
def __init__(self, client):
self.client = client
permission = SlashCommandGroup("permission")
@permission.command(description="Get the profile picture of a user > Skyler")
async def admin(self, ctx, role:discord.Role):
if ctx.message.author.guild_permissions.manage_messages:
db = sqlite3.connect('main.db')
cursor = db.cursor()
cursor.execute(f"SELECT admin_id FROM Permissions WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO Permissions(guild_id, admin_id) VALUES(?,?)")
val = (ctx.guild.id, role.id)
embed = discord.Embed(description=f" You successfully set Admin role **{role.name}**", color=0x23d953)
embed.set_author(name=f"{ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar)
await ctx.respond(embed=embed, ephemeral = True)
elif result is not None:
sql = ("UPDATE Permissions SET admin_id = ? WHERE guild_id = ?")
val = (role.id, ctx.guild_id)
embed = discord.Embed(description=f" You successfully set Admin role **{role.name}**", color=0x23d953)
embed.set_author(name=f"{ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar)
await ctx.respond(embed=embed, ephemeral = True)
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()```
how do i fix my error
hmm
"amount" automatically converts to str, so it raises error
async def ban(self, ctx, amount: int = None)
so int(amout) ?
clear
i changed itr
you can do that, but its easier to assign the type int to the argument
and how can i make this clear command more "appeling"
Hi, could someone help with this please?
the amount arg
async def clear(self, ctx, amount = None):
as in this
@frank wadi
anyone?
error?
yes
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: '>=' not supported between instances of 'str' and 'int'
import discord
from discord.ext import commands
from discord.commands import SlashCommand
from discord import default_permissions
client = commands.Bot()
class clear(commands.Cog):
def __init__(self, client):
self.client = client
@client.slash_command(name="clear", description="clears a specified amount of messages")
@default_permissions(manage_messages=True)
async def clear(self, ctx, amount = None):
if amount == None:
embed=discord.Embed(title="Clear Failed ❌", description="Please specifie how many messages you would like to delete ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
else:
if amount >= 1000:
embed=discord.Embed(title="Clear Failed ❌", description="Do not go over 1000, /purge for 1000+ messages ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
return
if amount <= 0:
embed=discord.Embed(title="Clear Failed ❌", description="I cannot delete zero messages ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
await ctx.guild.clear(amount)
em = discord.Embed(title="Cleard messages Successfully ✅", color=discord.Color.dark_gold())
em.add_field(name="cleard amount", value=f"{amount}")
await ctx.respond(embed=em)
def setup(client):
client.add_cog(clear(client))
and heres all my code
yes
you have a slash command, typehint amount with int
amount: int = None
^
never seen this
before
it dont work
no errors tho
await ctx.guild.clear(amount)
em = discord.Embed(title="Cleard messages Successfully ✅", color=discord.Color.dark_gold())
em.add_field(name="cleard amount", value=f"{amount}")
await ctx.respond(embed=em)
i belive its this
use discord.Option tbh
why
cuz its not responding
wait what is guild.clear
await ctx.channel.purge(amount)
Is there a way to make my bot retrieve the usernames of all users who have a specific role?
can i host with
something host with pycord?
cuz i bought it
nah it still aint working
im rebuild code to be in options
users = [x for x in ctx.guild.members if your_role in x.roles]
ty
can i get help real quic
import discord
from discord.ext import commands
from discord.commands import SlashCommand
from discord import default_permissions
client = commands.Bot()
class clear(commands.Cog):
def __init__(self, client):
self.client = client
@client.slash_command(name="clear", description="clears a specified amount of messages")
@default_permissions(manage_messages=True)
async def clear(self, ctx, amount: int = None):
if amount == None:
embed=discord.Embed(title="Clear Failed ❌", description="Please specifie how many messages you would like to delete ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
else:
if amount >= 1000:
embed=discord.Embed(title="Clear Failed ❌", description="Do not go over 1000, /purge for 1000+ messages ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
return
await ctx.channel.purge(amount)
em = discord.Embed(title="Cleard messages Successfully ✅", color=discord.Color.dark_gold())
em.add_field(name="cleard amount", value=f"{amount}")
await ctx.respond(embed=em)
def setup(client):
client.add_cog(clear(client))
it wont respond or delte messages
not errors
@gilded widget
?
#help-rules man, please stop pinging me
ok
use Option instead of int
async def clear(self, ctx, amount: Option(int, "description", required=False, default=None):
dont forget to import Option from discord.commands
i dont wanna use options
Hi, I'm getting None for all guild scheduled_events.creator, although scheduled_events.creator_id does work. I have enabled all Intents (super().__init__(intents=discord.Intents().all()))
dude its not gonna worl
the bot dosent want to respond
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: _TextChannel.purge() takes 1 positional argument but 2 were given
bruh
now im getting this
import discord
from discord.ext import commands
from discord.commands import SlashCommand
from discord import default_permissions
client = commands.Bot()
class clear(commands.Cog):
def __init__(self, client):
self.client = client
@client.slash_command(name="clear", description="clears a specified amount of messages")
@default_permissions(manage_messages=True)
async def clear(self, ctx, amount: int = None):
if amount == None:
embed=discord.Embed(title="Clear Failed ❌", description="Please specifie how many messages you would like to delete ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
else:
if amount >= 1000:
embed=discord.Embed(title="Clear Failed ❌", description="Do not go over 1000, /purge for 1000+ messages ❌.", color=discord.Color.dark_gold())
await ctx.respond(embed=embed)
await ctx.channel.purge(amount)
em = discord.Embed(title="Cleard messages Successfully ✅", color=discord.Color.dark_gold())
em.add_field(name="cleard amount", value=f"{amount}")
await ctx.respond(embed=em)
def setup(client):
client.add_cog(clear(client))
im so conffused
dude
this shit makes no sence
await ctx.channel.purge(limit=amount)
Speaking of clearing messages, is there any way to clear a specific member's messages other than my current method?
Current method:
# amount is the specified number of messages to clear
# member is the spcified member whose messages should be cleared
total_msg_count = 0
member_msg_count = 0
async for msg in ctx.channel.history(limit=None):
total_msg_count += 1
if msg.author == member:
member_msg_count += 1
if member_msg_count == amount:
break
await ctx.channel.purge(limit=total_msg_count, check=lambda message: message.author == member)
ok but when i throw a return on my if
it fails
omg im so fucking stupuid i had my return in the wrong spot
lmao
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "D:\All Codes\testobt\cogs\slash_commands\utilities\normal_cmds.py", line 67, in edit_embed
await i.response.send_modal(EmbedModal(self.channel, True))
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 897, in send_modal
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
``` 🤔
how should i handle this modal?
how do i install from the latest github repo?
ohk
any1?
use MemberConverter
it will return user object in any way you pass arg, raw id, name#tag or mention, then , then get id using, user.id
are there docs for it, since I’m pretty sure to pyc?
yes search em out
?rtfm memberconverter
I couldn't find a documentation with the name memberconverter! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc memberconverter
yes
can you give me a quick example on how to use it?
any1?
await Converter.convert(ctx, thing_to_convert)
Install instructions are on the github. just scroll down a bit.. You dont really need to install from github tho
how to remove file in message?
i tried to do it like this:
await message.edit_original_message(content=f":white_check_mark: {gdset_sucess[leng]}",file=None,embed=embed_set_img,view=None)
but no working
Error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'fp'
can you show the full traceback
help pls
Are you on Mac? IF so use this https://stackoverflow.com/questions/40684543/how-to-make-python-use-ca-certificates-from-mac-os-truststore
else use MigMatos solution below
what happens if you leave the file kwarg out?
update windows, i had the same error and it was because a certificate expired
I think its mad because its trying to do stuff with None
send a empty file lol
await message.edit_original_message(content=f":white_check_mark: {gdset_sucess[leng]}",embed=embed_set_img,view=None)
Sends that image above?
i use mac os and it's the newest version
use my link, to fix it than
yep
async def read_image(path):
with open(path,"rb") as image:
img = io.BytesIO(bytearray(image.read()))
file = discord.File(img, filename=path)
return file```
I tried removing ```file=None``` in message and nothing
Traceback (most recent call last):
File "applebuild/main.py", line 25, in <module>
bot.run(token)
File "applebuild/venv/lib/python3.10/site-packages/discord/client.py", line 715, in run
return future.result()
File "applebuild/venv/lib/python3.10/site-packages/discord/client.py", line 694, in runner
await self.start(*args, **kwargs)
File "applebuild/venv/lib/python3.10/site-packages/discord/client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "applebuild/venv/lib/python3.10/site-packages/discord/client.py", line 599, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: 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.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
You need to enable intents from the link in your error
works thanks
Sorry I am unsure about this.
I have a felling that None should work but there is a lib bug
Hi, I'm getting None for all guild scheduled_events.creator, although scheduled_events.creator_id does work. I have enabled all Intents (super().__init__(intents=discord.Intents().all()))
thx for trying helping :)
i better consider putting the image inside the embed and removing it along with it
that would work, You could also open an issue on the github to get it fixed so that None would work
I consider the same, since it works with views but files no
wait i have one more test
👀
👀
👀 try it
thxxxxxxxxxxxxx this works, I changed the code and works<3
try it
total_msg_count,member_msg_count = (0,0)
async for msg in ctx.channel.history(limit=None):
total_msg_count += 1
if member_msg_count >= amount:break
elif msg.author == member:member_msg_count += 1
await ctx.channel.purge(limit=total_msg_count, check=lambda message: message.author == member)```
I meant if there’s any way to do it without first iterating through the server messages to check how many messages to check before actually purging the messages, but thanks 😅
oh sorry i'm not very good at english, i have no experience in purging messages but i tried to simplify code
uhmm
AttributeError: module 'discord' has no attribute 'default_permissions'```
@discord.default_permissions(
administrator=True
)
async def apply(ctx):
await ctx.respond(view=MyViewModal())
from discord import default_permissions
@default_permissions(administrator=True)```
Update pycord to 2.0.0rc1
for this, can I use the role ID?
or would I need to get the guild ID then get the role using the Role ID?
works ty
one sec
ohh I think I figured it out? guest_role = ctx.get_role(*insert role ID here?*)
so
To add a role to someone best way is this:
role_name = get(ctx.guild.roles, name=role_name) (you can use id=0000000000000 as well)
await ctx.author.add_roles(role_name, reason="reason")
tyty and instead of author, can I replace that with the user I took in as an option?
great, thanks for the help \o/
hm, it says get is not defined?
discord.utils.get or import it
my bad lol
all good lol, just started this all up yesterday so am still figuring stuff out
sometimes in the code here you'll see people import stuff to shorten it or just use long paths like
discord.utils.get()
ooo
tyty
If you're new the best place to check is the docs
what I just import the whole thing?
Pydocs or Discord Dev Docs?
https://guide.pycord.dev/getting-started/creating-your-first-bot
https://docs.pycord.dev/en/master/api.html?highlight=attach#id10
https://docs.pycord.dev/en/master/api.html?highlight=attach#discord.Member.add_roles
Excited to create your first bot? Once you install Pycord, you can start right
yepp, been using these two \o/
you can choose how to style your code
get(ctx.guild.roles, name=role_name) vs discord.utils.get(ctx.guild.roles, name=role_name)
doing first way lol
then add the imports at top
Something you'll notice (im new too) is theres many ways of doing the same thing
also do I need to import discord.ext if I only plan to use slash commands?
from discord.ext import commands
from discord.commands import slashComamnd
tyty
@bot.slash_command()
async def test(ctx, member: discord.Option(discord.Member)):
await ctx.respond(member)
simple way of making slash command called /test that takes a member input
yep yep, I made one that kicks everyone in a role py @bot.command(name = "remove", description = "Kicks all the people in a specified role", default_member_permissions = discord.Permissions(kick_members=True, ban_members=True, moderate_members=True, manage_messages=True,)) async def kick(ctx, reason: discord.Option(str, "Enter the Reason for using this command if you want", required = False)): guildx = bot.get_guild(stuff) role = guildx.get_role(stuff) for member in ctx.guild.members: if role in member.roles: # does member have the specified role? await member.kick(reason=reason) return await ctx.respond("Done")
wait is it discord.Member or discord.User?
Because this is what i'm using rn user: discord.Option(discord.SlashCommandOptionType.user
guys do you know how to create a private response?
ephemeral=True
ty
await ctx.respond(embed=embed,ephemeral=True) is an example
i think either is fine
if it works then it works
true lmao
discord.SlashCommandOptionType.user will return discord.Member too
the one i use is just less wordy
woah
I like the code
worked \o/
have no idea, saw someone else do it. Basically just needed it to get the role but after seeing the get(ctx.guild.roles, id=stuff) way, I'll replace it with that
ctx.guild will basically get the guild the command was ran
yep, which is ideal
I previously had it have the option for any role but the Owner of the server said it was too risky which is valid
you can also add
@discord.commands.guild_only() as well
cause i assume commands probs visible in dms unless you got debug_guild as a value
oh, yeah true. Was wondering also how to only specify it to a specific guild
yep I do
in production you probs wont have that there
Slash commands takes upto an hour to register unless its a debug_guild
interesting
So instead of doing @bot.command(name = "remove") I'd do @bot.command.guild_only().(name = "remove")?
separate line, okay makes sense
they're called "decorators"
can I make it so that command only shows up in that guild using the guild ID?
Like it shows up in one guild but not the other
yeah
@bot.slash_command(name,description,guild_ids=[])
name and description isnt needed in the decorator but if you prefer it then go ahead
Yeah I always add them in lol
atm i assume you're just making one big file
later on you'd come across cogs which is slightly different. For now just learn how to do stuff then look into cogs as a way to splitting into pieces and stuff
Hello! I am switching to Pycord from discord.py and I assume almost everything which is currently in DIscord.py is already there in Pycord?
pretty much
https://guide.pycord.dev/getting-started/creating-your-first-bot
docs is a good place to learn but yeah
Excited to create your first bot? Once you install Pycord, you can start right
ooo will do
there are some breaking changes you need to keep in mind though
heard a bit about cogs but I feel like it's a little early to get into them
Pycord installs Discord.py or something
no it doesnt
ye i saw that alr, but just wanted to confirm everything works from discord.py -> pycord right
are there any breaking changes in cogs?
no idea lol, I know almost nothing about them
oh wait nvm that was a replit issue lmao
ah nvm then
cogs are the exact same
ah noice to hear
not really
could you tell me about the big breaking changes?
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
in cogs you'd use things like @commands.command() and add "bot" becomes self. you'd have to add "self" as the first parameter then other params like ctx etc
thats been the thing in dpy
it is the same!
ah nvm i shouldnt be answering two ppl at the same time
i was explaining to @wintry python how cogs work rather than you raj sorry
Basically theres not many changes. You just need to change a couple things and it'd work. Just read docs and read up how Pycord differs in some stuff and you're good
for some reason i can't get Modal from discord.ui as well as InputText
ah k! tysm
ah I seee
it can be kinda confusing first time but you get the gist
happy to help
can you show example code
mhm mhm, will do more research into it later. For now, I shall finish up this command lol
and I'm so confused on what is going on
What version is your py-cord?
what errors do you get?
sure lemme try, I mean is it bc the rc1 supports only slash commands?
prefix and slash commands stuff work in rc1
https://github.com/Pycord-Development/pycord/releases
explains what each release does
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
can you show code?
from discord.ext import commands
from discord.ui import View, Modal, InputText
import discord
import information as I
bot = commands.Bot(command_prefix = "?")
class MyForm(Modal):
def __init__(self):
super().__init__("Flight Announcement")
self.add_item(InputText(label="Short Input",PlaceHolder="PlaceHolder"))
class MyView(View):
def __init__(self,ctx):
super().__init__(timeout=3)
self.ctx = ctx
@discord.ui.button(label="Flight Announcement", style=discord.ButtonStyle.blurple, emoji=":cool~1:") #Work on expanding this to make it universal
async def button_callback(self,button,interaction):
button.style = discord.ButtonStyle.red
button.disabled = True
await interaction.response.edit_message(view=self)
async def on_timeout(self):
for child in self.children:
child.disabled = True
child.style = discord.ButtonStyle.red
await self.message.edit(view=self)
async def interaction_check(self,interaction):
if interaction.user != self.ctx.author:
await interaction.response.send_message("Invalid",ephemeral=True)
return False
else: return True
@bot.command()
async def flight(ctx):
View = MyView(ctx)
View.message = await ctx.send(I.Announcement,view = View)
@bot.command()
async def Menu(ctx):
Form = MyForm(ctx)
Form.message = await ctx.send_modal("Hello",view = Form)
So when you use your comands nothing happens?
yup
the flight thing works, i need to finish the menu command
but downloading the new versions are making it not work#
add debug_guilds=[id] to your bot thing
what hosting doe @supple ravine use
bot = commands.Bot(command_prefix = "?",intents=discord.Intents.all(),debug_guilds=[server_id])
also change def Menu to def menu
no clue. why?
if you want free hosting google oracle's free VPS
it has errors now
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
oh wait
bot = commands.Bot(command_prefix = "?",intents=discord.Intents.default(),debug_guilds=[server_id])
no its not that im using somethingcp but one of its nodes are limited
U need message content intents im pretty sure
cuz it got banned by discord
lmao i see
Cut Your Cloud Bills in Half Deploy more with Linux virtual machines, global infrastructure, and simple pricing. No surprise bills, no lock-in, and the
prob could use this too
I prefer using my oracle vps rather than credits lmao
I have pycord downloaded and import python
@bot.slash_command
is it any good?
I have my bot set to client
@bot.slash_command()
async def test(ctx, member: discord.Option(discord.Member)):
await ctx.respond(member)
example slash command
ye ik im looking at the docs
full code?
u got cogs?
Does this give you enough resources to run ur bot 24/7?
you just put
import discord
make sure u imported slash commmands
💀 you can get 24 gigs of ram and 4 oCPU's. I hope thats more than enough
from discord.commands import SlashCommand
ah. how do i do that
nope it still has the same error
Is that in the always free tier?
just import from discord
import discord
import os
from discord.ext import commands
from discord.commands import SlashCommand
client = commands.Bot()
this is my main
setup
buti use cogs
same i do too
show all code
i wanna see it
uhh its pretty long
wait
just the slah command
import discord, requests, json, sqlite3, os, asyncio
from discord.ext import commands # Imports required Modules
from mcstatus import MinecraftServer
from dotenv import load_dotenv
from pathlib import Path
from discord.commands import SlashCommand
intents = discord.Intents.all()
intents.members = True
load_dotenv(dotenv_path=Path('data/.env'))
client = commands.Bot(command_prefix=prefix, intents=intents, help_command=None, case_insensitive=True) # Setting prefix
@client.slash_command(guild_ids=[894902529039687720])
async def test(ctx):
await ctx.respond("Hello!")
client.run(os.getenv("DISCORD_TOKEN"))
@client.slash_command(name="clear", description="clears a specified amount of messages")
@default_permissions(manage_messages=True)
ui forgot
u have to define the slah command
thats mine
oh shit-
change if for yours
it gives a error in the import thoo
hmm
hold up
pip uninstall discord.py
pip install py-cord
try
i can send pip list too if you want
pip install -U py-cord==2.0.0rc1
ah got it
imagine using pycharm 🤓
😭 it looks clean
no it dose not
litteraly the uglist ui ive ever seen
this is mine it looks so much better
i would recomend using vscode
i love vscode
I use VScode too, but for everything except py lol
why
its pretty much meant for py
and js
Hey my bot isnt starting i get this error (or message) in console
DEBUG:discord.client:on_ready has successfully been registered as an event
DEBUG:discord.client:on_application_command_error has successfully been registered as an event```
isntall voice
async def on_message(message, m=None):
if '!help' in message.content:
embed = discord.Embed(title="Hilfe", description="Melde dich bitte bei Juvani#9744!", colour=0xff0000)
await message.channel.send(embed=embed)
if message.content.startswith('!userinfo'):
args = message.content.split(' ')
if len(args) == 2:
member: Member = discord.utils.find(lambda: m,args [1] in m.name, message.guild.members)
if member:
embed = discord.Embed(title='Userinfo für {}'.format(member.name),
description='Hier siehst du alles Infos über den User {}'.format(member.name),
colour= 0xff0000)
embed.add_field(name='Server beigetreten', value=member.joined_at.strftime('%d/%m/Y, %H:%M:%S'),
inline=True)
embed.add_field(name='Discord beigetreten', value=member.created_at.strftime('%d/%m/Y, %H:%M:%S'),
inline = True)
rollen = ''
for role in member.roles:
rollen += '{} \r\n'.format(role.mention)
if rollen:
embed.add_field(title='Rollen', value=rollen, inline=True)
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text='Das waren die wichtigsten Infos!')
await message.channel.send(embed=embed)```
vscode can code in pretty much anything as long as the relevant extensions are available
alr
py path issues, but ill check it out
i can help with that
What does voice do?
WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported
so u dont get this error
Traceback (most recent call last):
File "C:\Users\ndert\Desktop\Juvani\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ndert\Juvani\main.py", line 30, in on_message
member: Member = discord.utils.find(lambda: m,args [1] in m.name, message.guild.members)
AttributeError: 'NoneType' object has no attribute 'name'```
whats wrong in my code?
None = the member wasnt found
kwargs
hm? whats that?
key word arguments
Hey i still get
DEBUG:discord.client:on_ready has successfully been registered as an event
DEBUG:discord.client:on_application_command_error has successfully been registered as an event
I installed voice, do i need to add any code or?
show line 30
nah
should have too
u getting any errros?
Nope
try using your command
its just telling u that stuff worked
member: Member = discord.utils.find(lambda: m,args [1] in m.name, message.guild.members)
yeah but it dosent go online
idk lmao
ask some one else
okay
The bot isnt online and hasnt added it either
is your token correctr
yes
and u using client.run on the bottom
Oh i fixed it, I accdeintly added an indent or 2 on bot.run
Try member: Member = discord.utils.find((lambda m: args[1] in m.name), message.guild.members)
can you help me
ive installed pycord
and discord still isnt a module
its just a known issue
i get it too
its nothing to be worried sabout
how do i fix it
cause my bot wont run it
it says its not installed
When using the message history, is there an alternative way to get the message’s content without the message content intent with the REST api? And if I can use the rest api to get the content without the intent, how do I do that with pycord?
nope. you can only see message content without the intent if the bot was pinged or if it was in the bots dms
I was told you can use the REST api
Not Pycord related
Oh
how else do you think bots work if the api didnt exist?
You can't
It's limited by discord, not Pycord
No, I mistook it with another api...
restart ide
@red tendon
fyi dont ping people
we are not obligated to help
doesnt work btw
yes ive read it
hello, does anyone know why i get this error?
cannot import name 'commands' from 'discord.ext' (unknown location)
i'm trying to migrate my old discord bot from discord.py to pycord but i don't know what module should i use insted of that?
did you not uninstall dpy prior to installing pycord?
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
i have
one second
i've uninstalled it, basically i've just reinstall my hole windows and i don't think that i have any other modules installed
Did u install pycord?
yes
Which version?

how do I check if the bot tries to delete 50 messages and t heres less than 50 messgaes say something
how do i check that
or really any number
what are you using to delete the messages? purge?
I had even use an If to check if the bot is connected to VC it's returns True and Then gives this error

can you show the code that's raising this error
sure
Hi, for on_scheduled_event_update(before, after), I'm getting NoneType for before. Is there any reason why?
are you also getting None for after? or just before
Just before
@Cog.listener()
async def on_scheduled_event_update(self, before, after):
print("update", before, after)
Yes I had this problem before as well
In older Pycord versions
how do i make slash cmds within cogs?
from discord.commands.core import slash_command
from discord.ext.commands import Cog
class ACog(Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(guild_ids=[Guild_ID], description="Foobar")
async def foo(self, ctx, bar):
await ctx.respond(bar)
def setup(bot):
bot.add_cog(ACog(bot))
what's the diff between respond and reply?
respond just sends the message, reply replies to the msg
async def info(ctx):
ctx.send('Hello! Here is some useful infomation about me.\n I run through slash commands and i am created by jack. here is my commands \n /ip - Sends our minecraft SMP IP \n /ping - Stats of the bot \n /nick - Used to change someones nickname \n /say - Sends a message of your choice through the bot \n /bean - Fake bans someone \n /dm - dms anyone your chosen message through the bot \n ')``` Why isnt my bot sending the message after /info
ah k, also how do i make input for slash cmds?
await ctx.send()
You're not awaiting the response
i did it w respond and it never worked either
seemingly a lib bug, might be best to report it on the github https://github.com/Pycord-Development/pycord/pulls
The same way it works for normal commands.
async def command(ctx, option1: str)
You're in a slash command, you use ctx.respond
okay
👀 thanks
do i have to modify anything in the @commands.slash_command statement
This hasnt fixed it
dont have an error
Nope.
Then what's happening
I just get 'Application did not respond' no errors in console
you didn't await it
Code?
Btw ive fixed it but i did send my code lmao
You sent old code. Which you were told to await and then told to switch send to respond
is ctx.respond the eq of ctx.send in discord.py?
no, send and respond are very different
what's the diff?
send is a generic function used for any "Messageable" object (users, channels etc.)
ctx.respond is a response to an interaction, and is a shortcut for ctx.interaction.response.send_message
which is required when working with slash commands
ah
Btw, is there any way to purge a specific member's messages without first iterating through channel messages to get the amount of messages to check?
@commands.slash_command(name="embed", description="Sends a nice looking customisable embed", guild_ids=[guild_id])
async def sendembed(self, ctx, title: str, content: str):
This doesn't work, any idea?
total_msg_count = 0
member_msg_count = 0
async for msg in ctx.channel.history(limit=None):
total_msg_count += 1
if msg.author == member:
member_msg_count += 1
if member_msg_count == amount:
break
# ie: is there any way to do it without the code above?
await ctx.channel.purge(limit=total_msg_count, check=lambda message: message.author == member)
huh
You can run checks on TextChannel.purge
am i supposed to like include some input option thing in @
How would I make sure it only purges a specific amount of messages for a specific member?
ehhh
can someone help me man