#discord-bots
1 messages ยท Page 186 of 1
no, I personally don't have a solution, we're in the same boat 
yeah
.....
I mean you could try but I'd prefer making a single connection first and trying, so many unclosed connections may mess up the file and corrupt it at the end of the day 

Ye
okay
Use db visualizer to inspect the db file
ive tested this all before
it all worked and now all of a sudden there is an error
(I didnt change anything)
okay!
just make a single connection

so many connections is resource consuming and makes the file prone to corruption
It auto-closes after the context manager ends
yes
Oh it's using async
๐i forgor totally
with open(file....) as ash:
Do the same lol
,

hey Catgal, type pip install invoke, i am not weard, i am a yang PetoNYst:)
May someone explain this to run the slash commands>
await client.tree.sync()
``` I cant find it in the docs
Code?
what is the problem here?
the process is terminated because it's using too much memory?
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
how to turn off @ everyone but allow mentioning of specific roles?
You can change this in your server settings
async for entry in g.audit_logs(limit=1,after=datetime.datetime.now() - datetime.timedelta(minutes=2),action=discord.AuditLogAction.bot_add):
why isnt this working nothing is logged
yea but i am confused which settings to turn off @ everyone universally and to turn on specific roles
Maybe you need to enable the community first
Then go to the role that you want others to mention
It will disable @ everyone
does community automatically disable everyone
help me also
oh ok
I guess
@vocal hollow
Check the second option if you want a specific role that can be @ by anyone
ignore,,,
Hewo
who is from which country?
Remove after...
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guildโs audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...

anyone familiar with sqlite?
Ye?
how to check if a user who is using the cmd has a banner or guild avatar
!d discord.Member.default_avatar
property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.default_avatar "discord.User.default_avatar")
!d discord.Member.banner
property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.banner "discord.User.banner")
!d discord.Guild.icon
property icon```
Returns the guildโs icon asset, if available.
Here
Check this 3 prooerties
Properties*
okay
to find if a bot on discords is open source should one search on github
or are there other ways to know if the bot is free or more info on it
I am also curious if Discords has access to source code of all bots?
Discord just sends events to bot and bot sends requests, how can discord have access to source
They typically put it into description or on site
Most of mega-popular bots like dyno and mee6 aren't open-sourced yk
Mhm
You can look into this one, pretty qualite code ๐ค https://github.com/BobuxBot/BobuxAdmin
so I wonder what if the bot didn't have link to info or github source code, how to get info on it?
If they didn't put it there it's most likely not there
so no way to get info or source code on it?
๐๐๐
Why are you so obsessed with that
I like different bots from different servers
There are tons of open-source bots just search until you find one
Just make one yourself :)
I hope to create my own server soon but dont know if I can do all the bots I want
I think its faster if I can copy them but sometimes I dont see info on it
Some of them has copy of whole popular bot, ex: carl bot
but from what I am understanding, discords bot is actually similar to twitter bot
it seems a lot of bots use python
They all use almost the same mechanism
Platform sends events to app, app sends requests to platform
Not a surprise, everything functions like that
I see, so seems learning discords bot skill will translate to other kind of bots
If you learn principle, not only library
python principle or others?
hmm do most API use python?
discords API is python or could it also work with others, not sure actually
but yes I do think I need to learn more about API interactions principle as I plan to use bots and API in general
one great thing about this field is since code can be on your own private server, maybe it can't be copied as easy as javascript
I remember debating someone about this, but I think they mention javascript had their own server backend so not sure, I guess all languages are similar in a way, but I chose python for now
Discord API is itself made with js, but information the API give us, we can make the bot with any languages, python, js, golang etc etc
oh interesting, didn't know that, thanks
so some discords bots may be harder to manipulate if programmed in a language you dont know
Yes
If u r wondering there is several python libraries, where they parsed all informations from the API and made it usable for normal users
For example discord.py or disnake
I see, I am now wondering if someone got in trouble for copying someone bot and server? is it okay to do that I hope
depends on how you define copy
if you straight up take their source and shit yeah. that can prob get it taken down
discords has ban users for that?
I think this is why we need decentralized discords to become more popular
once things are decentralized, no one owns them and can ban people
For violating discord TOS
If the bot owner gives you the source or make it public or give you perms, then u good to go
You can steal bot code lol?
Why not steal the whole bot lol
Like making a same type of support server as apollo
Copying their bot's pfp etc
depends on intent
Lol
they wont ban if its just a mimic but if its for malicious intent thats different, either for users or towards the real bot
Intention hm
I understand now but mimicing I don't think could get you in trouble
Yea fr
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/myname/Custom bot/cogs/add.py", line 20, in add
await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
^^^^^^^^^
AttributeError: 'AddCog' object has no attribute 'guild'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/bot.py", line 1381, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'AddCog' object has no attribute 'guild'```
nextcord.utils.format_dt(datetime.utcnow(), style="R")
class AddCog(commands.Cog):
def __init__(self, callisto):
self.bot = callisto
@commands.command()
async def add(self, ctx, member:nextcord.Member):
async with aiosqlite.connect("callisto.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
await cursor.execute('UPDATE users id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO users (user_name, id, guild) VALUES (?, ?, ?)', (f"{member.name}#{member.discriminator}", member.id, ctx.guild.id,))
await db.commit()
def setup(callisto):
callisto.add_cog(AddCog(callisto))```
U r using cog
yeah
And since self is required
OH
haha
omg
ahh thats embarrassing
quick delete all evidence
Nah np lol
quickly
Yes fast 
umm new error now
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/bot.py", line 1381, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: near "id": syntax error```
but theres no syntax error
Does anyone know reasons why a discord bot wouldn't work when printing that it's online and not giving any error?
^
show code
Told u to use "" on queries
And '' on values
yes but it doesnt work then ๐ญ
nvm I fixed it
Ig #databases
I think it was do to me having an on_message event that only had pass inside of it
yeah if you are using an event and not a listener then you have to process_commands
How to set dynamic cooldown in a cog?
Can't get access to self arg
Just define the func outside the class
bbutton.style = discord.ButtonStyle.gray, disabled = True
any way how to get this to work, it doesnt disable the button
That defies the purpose of getting the self arg
Why do you need that anyway
Just separately set them
oh ty
to get access to bot obj?
if user.banner == None:
bbutton.style = discord.ButtonStyle.gray
bbutton.disabled = True``` even though i have a banner it disables the button
Working on an action log command, it works as intended but it doesn't pick up on messages that are only attached images or a hybrid of text and image. How can I edit my code so it also detects attached files?
@bot.event
async def on_message_delete(message):
if message.author.bot:
return
embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**\n{message.content}", color = 0xf6ff00)
embed.set_author(name = f"{message.author.name}#{message.author.discriminator}", icon_url = message.author.avatar)
embed.set_footer(text = f"User ID: {message.author.id} โข Message ID: {message.id}")
channel = bot.get_channel(<the action log channel>)
await channel.send(embed = embed)```
!d discord.ext.commands.Cog.cog_check
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
The bot that contains the command being executed.
I guess ๐คท
anyone gave example how to write voice data from channel to buffer queue?
while True: data = q.get() -NICE:)
how to fetch a user in cogs
Afaik only nextcord supports voice receive if you mean that
yes i am using nextcord
i need RawInputStream from channel ID ๐ to the buffer, now i am using sounddevice for this but this is not right way
buser = await bot.fetch_user(member.id)
doesnt fetch the user in cogs should i define bot in cogs too?
Take the bot instance in the cog _init_
okay ty
;-;?
Yeah too spooky
Yep lmao
Just an advise โ don't create new connection for every query. Have one connection established on bot launch and close it on bot shutdown
UPDATE users id = ? WHERE guild = ? is invalid
What are you even trying to achieve
Monin 
fill in the blank:
mo_ning
a
It's definitely a
!e print("mo_ning".replace("_",import("string").ascii_lowercase[int(import("math").log(1,69420)69(420+6+ 9**6))]))
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
moaning
Tbh outside of code block it looks even more sus
wtf
oh
with open("image.png", "rb") as f:
data = f.read()```
how i convert this data to png ?
and then png to discord file ?
data to png? what do you mean
what is your actual goal? Do you want to send image.png to a discord channel?
How do I change a global variable from within a tree.command
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
that way you can use interaction.client.<var> to update it anytime
Sending image is as easy as send(file=discord.File("path/to/file"))
i want to make my code more clean and... readable, so learning about cogs
How can I stop a tree.command from continuing to run at a specific point in it?
I thought about using break but thats only for loops
return?
the moment i posted my code i saw the error lol
hello I have a little question, Ive been tryint to import discord_components
but its saying:
Traceback (most recent call last): File "c:\Users\Kynhogat\Desktop\kyn_end\main.py", line 12, in <module> import discord_components ModuleNotFoundError: No module named 'discord_components'
I tried to install it using pip but:
ERROR: Could not find a version that satisfies the requirement discord-components (from versions: none) ERROR: No matching distribution found for discord-components
I hope someone can help with it, ty!
are you using discord.py?
yup
thank you very much ๐
i have few functions in my bot
they are not commands but they are just like normal functions like in basic python
They are just randomly lying around in my code
is there any better way to write them?
you could put them in a separate module and/or utilize classes
i can try classes
await ctx.send(embed=hell.main, components=[[Button(style=ButtonStyle.blue, label="Main", disabled=True),
Button(style=ButtonStyle.blue, label='test'),
Button(style=ButtonStyle.blue, label='Games')],
[Button(style=ButtonStyle.blue, label='Lock'),
Button(style=ButtonStyle.red, label='test'),
Button(style=ButtonStyle.green, label='Admin')]])```
is this the right use of the buttons?
because I am getting the error: Button isnt defined
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
this is the class ^
thank you
can i somehow make the member argument optional? like if the user doesnt provide a vailed member it jumps to amount
what i mean is the command should work in both ways
^ <- prefix
^set @wodgenzi_#2586 100
set 100
is it possible ?

yes, see the Optional[] special converter
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#typing-optional
okay thanks
Hello, how can I get the author who used this slash command?
async def test_command(interaction:Interaction, minutes:str):```
The user or member that sent the interaction.
Anyone have any idea why this code isn't working?
What exactly isnt working?
It does not react to the message
Does the bot have proper permissions?
Yes
Oh wait
The id has to be int, not str
Remove the quotes from the id
Done, but now it will react to every message, and I want it to react to the messages on a specific channel
You didn't have to remove entire condition
Just quotes around ID so it looks like this
if message.channel.id == 123456789012345678```
Oh ok
Hello, someone can help me to make my bot work? I cant get command working , that command should edit channel permission for specific user, its possible to do it ?
@vagrant crescentHello, do you understand python and nextcord things ?
nope
@vagrant crescentWho from staff knows ?
Why does it have to be specifically from staff?
@sick birchusually staff knows things
also I recommend showing your code, errors, expected vs actual behavior to maximize your chance of getting help
im new here, and second day trying create one command
@sick birchi opened forum with code
It's hard for people to answer questions with minimal information
and what im trying to do
Can you show us the code you have so far? What exactly do you want it to do? Is it behaving in an unintentional manner? Do you get any errors?
@slate swancheck in #1035199133436354600
Anyone knows how to solv it?
what's above that if statement?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
please paste the code, I cannot tell from screenshot
and no code inside the function
my bad I always forget about the paste thing

So what can I do to solve it xD?
well why do you just have a blank function there?
what i can do
I can't remove discord.py Because he is connected to it
are you using nextcord or discord.py
nextcord and discord.py
you're using both? in the same code/
what i can do
which discord.py functions do you require that are not present in nextcord?
and which nextcord functions do you need that are not in discord.py?
doesn't nextcord support application commands? why do you need discord.py for it
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
๐
They can never be used together ๐ฅฒ
no, because nextcord was designed as an alternative for dsicord.py
ok thx
you shouldn't ever need to use both together, because they support the same things
just in different ways
idk so just remove it?
neither do I
nothing comes up there? should i follow the discord py guide thing
Are you trying to learn Python or learn the discord.py framework
i'm trying to learn to code bots
so i think the discord.py?
then you should learn python first
where do i do that?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
could i follow the discord.py learning guide?
that only introduces the framework. If you don't know basic python (datastructures, functions, classes, etc) then you won't understand it
could you send me the first one and the third one?
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
I have my python installed weirdly which is preventing me from using pip (which doesn't allow me to download pip install discord)
which channel should I be using for help
(first: https://automatetheboringstuff.com, third: https://python.swaroopch.com)
invoke it with the python command, python -m pip install -U discord.py
I have pip (and discord) installed on my python install
however I cant change the version of python
I am currently forced to use Anocanda
do I need to update this?
oof I have no experience with this, sorry. You might want to claim a help channel
looks like your command has user parameter which you didn't pass when invoking the command in discord
Hey guys how do I make it so that the bot fines the user that deleted a channel?
this is what I have currently
"Fine" how?
!e discord.on_guild_channel_delete
!d discord.on_guild_channel_delete
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
note the arguments
smart, make people pay if they delete a channel and ban them if they don't
I want my discord bot to send a message to the person running the command how do I do it?
ctx.author gives you a Member/User object, you can .send to that
NameError: name 'ctx' is not defined
are you in a slash command?
yea
then you would use interaction.user
interaction.user.send ?
not working
are you getting an error?
no
can you show your code/
@bot.tree.command(name="tc")
async def tc(interaction: discord.Interaction, tc:str):
await interaction.response.send_message(f"{interaction.user.name} said: '{tc}' ")
print("1")
cur.execute("SELECT * FROM `data` WHERE `TC` = %s", (tc,),"")
print("2")
sonuc = cur.fetchall()
print("3")
for x in sonuc:
print(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))
await interaction.user.send(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))```
@vocal snow
so it's executing that print statement but not sending anything?
yes
no
opss
sorry bro i getting error
2023-01-27 02:38:38 ERROR discord.app_commands.tree Ignoring exception in command 'tc'
Traceback (most recent call last):
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\2k\Desktop\proje\deneme.py", line 34, in tc
await interaction.user.send(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'tc' raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
their DMs are closed probably
wait i try again
discord in a year
its crazy how plausible it is
TypeError: 'Member' object is not callable
well it isn't
why are you calling a Member object
did you forget the .send
we live in a society eh
Which is?
2023-01-27 02:46:03 ERROR discord.app_commands.tree Ignoring exception in command 'tc'
Traceback (most recent call last):
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\2k\Desktop\proje\deneme.py", line 34, in tc
await interaction.user.send(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'tc' raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
yeah, so their dms must be closed
no
so how do i send it to the channel
interaction.channel.send / interaction.response.send_message if you haven't responded to the interaction /
I read the document and I didn't get what I needed
interaction.response.defer + interaction.followup.send if you are unable to respond to the interaction within 3 seconds
ok tysm
and you can set ephemeral=True so only the command author will see the message. like a dm
@vocal snow
good mronign
good night
Trying to log when a member joins the server and it displays their account age (e.g. 1 year, 5 months... NOT the account creation date) and I get this error message when someone joins TypeError: can't subtract offset-naive and offset-aware datetimes
@bot.event
async def on_member_join(member):
now = datetime.utcnow()
delta = now - member.created_at
embed = discord.Embed(description = f"**{member.mention} joined the server**", color = 0xf6ff00, timestamp = embed.created_at)
embed.add_field(name = "Account Age", value = delta, inline = False)
embed.set_thumbnail(url = member.avatar.url)
embed.set_author(name = f"{member.name}#{member.discriminator}", icon_url = member.avatar)
embed.set_footer(text = f"User ID: {member.id}")
channel = bot.get_channel(1067413418597953637)
await channel.send(embed = embed)```
I think it's something to do with the line delta = now - member.created_at
use discord.utils.utcnow instead of datetime.utcnow to get an aware datetime
!d discord.utils.utcnow
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
Works better now, it displays the account age in days but it also shows 1:23:45.678910 after, so how can i remove that AND convert the days into years, months and days?
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; (b) with YouTubeโs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
oh, sorry
you can help with music bot's as long as it isn't against any of the stuff listed above.
@vocal snow
alot of ppl do radio bots and i even seen one guy doing local files with beats he made for like rap cyphers
Yes, but the code mentions youtube
No, we won't help with anything that utilizes ytdl or other such libraries
F
If it's a music bot that obtains music legally then it's fine
How can i make it so it displays the account age as "x years, y months and z days", and remove the 1:23:45.678910 that appears after it?
now = discord.utils.utcnow()
delta = now - member.created_at
embed = discord.Embed(description = f"**{member.mention} joined the server**", color = 0xf6ff00, timestamp = member.joined_at)
embed.add_field(name = "Account Age", value = delta, inline = False)```
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
use a timestamp
that won't display y months or z days though
https://pypi.org/project/humanize could work
Tried installing humanize and it wasnt working so i uninstalled python and reinstalled, then tried humanize again and it worked, but now my import discord and from discord.ext import commands wont install even if i type pip install discord in the temrinal since it just repeats requirement already satisfied...
Ill try restarting my pc, see if tha thelps
They can just click on the timestamp to get the exact time
Yeah restarting my pc didnt help
Then it's already installed
When i run the code i get ModuleNotFoundError: No module named 'discord'
<t:1674786819:R>
Show the log when you tried to install it
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ah, another python/pip mismatch
which IDE are you using?
Visual Studio Code
check the interpreter version (bottom right of your IDE) and see if the version matches output from pip --version
pip --version = 3.11
interpreter version = 3.10.9
then change the interpreter version to 3.11
click on the interpreter version and select 3.11 from the list that shows up
https://gist.github.com/n0Oo0Oo0b/8c12660aa08cb77bae00e8b043b76b5d#method-1-changing-the-pip-version I made a gist on it yesterday because it gets asked so often ๐
How to fix pip not installing packages even though it says 'requirement already satisfied' - pip-python-mismatch.md
?
the relative timestamp style exists
but even if you want to use a timedelta humanize is definately not the best way
well, it works ๐คทโโ๏ธ
Humanize works, but is it possible to round the seconds? age = humanize.precisedelta(delta)
Looking at the website and im not seeing anything on rounding
You better off making your own than keep finding
pip install discord is the mirror package
i don't know if that one has been updated try pip install discord.py
try minimum_unit="minutes"
where exactly do you see months or days in the relative timestamp
if my account was created on jan 26 2020 you will just see "3 years ago"
you just need to move your cursor on it?
and?
Seconds doesnt appear but minutes has decimals
I could add milliseconds so there's no decimals ig
you can't get it to work properly "according to your will" without making a custom parser
sarthh 
Ok nvm i have to go to microseconds if i dont want decimals lol, I'll just deal with the decimals in seconds
Thx for ur help though guys <3
๐
hi bye
is pycord or discordpy recommended over the other? is there a difference?
discord.py >>> pretty much any forks
discord.py is the most popular python library for handling the discord API, and i think its decently organized (specifically the newer features since thats where most forks of d.py deviate the most), but i cant say anything about the architecture of pycord and both libraries seem to be actively maintained
Is it possible for a bot to return "None" for their member.display_name if they do not have a nickname or will it always return their username UNLESS they have a nickname? (sorry if unclear)
!d discord.User.display_name
property display_name```
Returns the userโs display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
well the property says the return type is str, so None shouldnt be expected
discord.py's way of handling things is far better and consistency than pycord, py-cord is easier and provides additional features like built in pagination and voice recieve from discord...
but in general opinion dpy is more preferable
ok thank you @hushed galleon and @slate swan!
display_name is literally just ```py
member.nick or member.name
can you share your code?
^
yes
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
can you see that?
not my code helping for a freind
@austere prairie ^^^^
yeah we can't help with that, definitely breaks riot games tos
please can you its for a freind i just need help with the error code
!rule tos
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
yeah what zeffo said
dms
its not about that come on
just need help fixing the error code
doesn't matter, it still breaks the tos
its not that deep your not going to go to jail ๐ญ
still, rules are rules
so you wont even tell me what the error code its
I don't even know what the error is, I haven't seen that before
This seems to be a common issue I cant find the right answer for: I can get my bot to run its just that the @ bot.command() does not work. How can I resolve this?
have you enabled message content intents?
make sure message content is enabled in the dev portal as well
Yes I have
In my file and in the portal
I wonder if it has to do something with the order. But at the same time, the ide isn't throwing any errors
Order of my code*
do you have an on_message event?
I don't have an event, I only have the command and the function for the command
Great time to segue to something...
So y'all might know by know I'm the project lead for migrating pins from this channel to site
Additionally I'm also tasked with a few tags that could be useful in situations like these
For instance, a tag explaining why on_message blocks your command handler: !on_message
Or generally common pitfalls like these
I'm looking for some volunteers to help doing that, if you haven't contributed to our repos this would be a great first step.
Let me know if you're interested and I'll CC you in a formal announcement that I'm about to put together ๐
The work will be relatively easy as we want to tags to be pretty short
hey man can you help me? i need to find the version off this code i have not coded by me by a freind is there any way i can find out
Not sure what you mean by "version"
what version the discord bot was coded in
as i am using the newest version right now but this was coded some time ago
print(discord.__version__)
What command are you running?
print(discord.version)
does it matter where?
sorry i am very new to coding
Np
i cant find where you mean?
!pastebin your code please
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
sorry i would rather not show my code at the moment i know that might be a problem
We can't help you without seeing your code
Erm.. we're not going to be helping with a "Valorant Account Generator"
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
okay its all good not my bot as i said dont want to get in trouble
Attempting to polish my bot's audit log, however whenever I ban someone it sends both on_member_ban AND on_member_remove. Is there anyway I can make it so it's like "if member was banned, don't send the on_member_remove"?
@bot.event
async def on_member_ban(guild, member):
embed = discord.Embed(description = f"**{member.mention} has been banned**", color = discord.Color.red(), timestamp = discord.utils.utcnow())
embed.set_thumbnail(url = member.avatar.url)
embed.set_author(name = f"{member.name}#{member.discriminator}", icon_url = member.avatar)
embed.set_footer(text = f"User ID: {member.id}")
channel = bot.get_channel(1067413212955426877)
await channel.send(embed = embed)
@bot.event
async def on_member_remove(member):
now = discord.utils.utcnow()
delta = now - member.created_at
age = humanize.precisedelta(delta)
embed = discord.Embed(description = f"**{member.mention} left the server**", color = discord.Color.red(), timestamp = discord.utils.utcnow())
embed.add_field(name = "Account Age", value = age, inline = False)
embed.set_thumbnail(url = member.avatar.url)
embed.set_author(name = f"{member.name}#{member.discriminator}", icon_url = member.avatar)
embed.set_footer(text = f"User ID: {member.id}")
channel = bot.get_channel(1067413418597953637)
await channel.send(embed = embed)```
(For clarification the on_member_remove is for when members are kicked or leave the server themselves)
No convenient way
Personally I'd just leave it as it's pretty easy to infer
check if the member is in the bans list under on_member_remove maybe?
Do we know which comes first?
it will still dispatch the event though
well cant we just test and see, if its constant?
Sure can
?
await fetch_ban(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry") for a user.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Hm this may work
nah
well maybe
it depends like robin said which event comes first
and if it's constant
try:
await fetch_ban(user)
except discord.NotFound:
#rest of the code
Yep
yea but he is explicitly trying to only do one and not the other so if try fails that will still trigger both events
Yep lol
that's actually something I never thought of with the ban/remove events
Just incase if member get bans first then this code should work
If remove triggers first then ๐
Maybe u can use asyncio module too to give some delay, but idk if it would work lol
!d discord.Member.ban
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
Meh
helppp
yes
`@client.command()
async def setup(ctx, wlcmC: discord.TextChannel, byeC: discord.TextChannel, guildID: discord.Guild):
global wlcm
wlcm = wlcmC
global bye
bye = byeC
global guild
guild = guildID
print(wlcm, bye, guild)
@client.event
async def on_member_join(member):
await guild.get_channel(wlcm).send("Hello")`
this is not working
NameError: name 'guild' is not defined error
ok and
this is not working
read the error
i kknow
learn python
but i made the guild a global variable
so
don't use globals like that
๐ then why ask
BRUHH i mean i knew that im making the vars wrong way
!botvar use these
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
for me?
oh yea ok
i tried that also it didnt work lemme show
`wlcm: discord.TextChannel
bye: discord.TextChannel
guild: discord.Guild
@client.command()
async def setup(ctx, wlcmC: discord.TextChannel, byeC: discord.TextChannel, guildID: discord.Guild):
wlcm = wlcmC
bye = byeC
guild = guildID
print(wlcm, bye, guild)
@client.event
async def on_member_join(member):
await guild.get_channel(wlcm).send("Hello")
@client.event
async def on_member_leave(member):
await guild.get_channel(wlcm).send("Bye")`
bot_instance.wlcm = ...
what does this do anyways
makes the variables global, in a better way
welcome
Code works, but is there any way I can make it significantly shorter? I'm going to do similar types of code for other commands and I would like to know if there's a way I can save lines and time: https://paste.pythondiscord.com/oruyufopev
More specifically, embeds with varying images and titles depending on the random number landed on
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
Pick a string from a list then put it in the embed
`client.wlcm: discord.TextChannel
client.bye: discord.TextChannel
client.guild: discord.Guild
@client.command()
async def setup(ctx, wlcmC: discord.TextChannel, byeC: discord.TextChannel, guildID: discord.Guild):
client.wlcm = wlcmC
client.bye = byeC
client.guild = guildID
print(client.wlcm, client.bye, client.guild)
@client.event
async def on_member_join(member):
await client.guild.get_channel(client.wlcm).send("Hello")
@client.event
async def on_member_leave(member):
await client.guild.get_channel(client.wlcm).send("Bye")`
this doesnt work
!e print ("hello world")
@slate swan :white_check_mark: Your 3.10 eval job has completed with return code 0.
hello world
omg wow
!e print("Hello Hello")
@fresh fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello Hello
yo this is cool
@fresh fern @slate swan
use #bot-commands please
k
sorry
I genuinely read that as "I am sorry" ๐ wtf
how have you defined avatarowner?
Hello, How would i make my bot status say watching number of ticket
you can change the status using change_presence
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientโs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
Err, No i just want it to say watching number of tickets
yes, so you use that method to change the status to say whatever you want it to say
How would i make the bot do it automatically?
you could change it whenever a ticket is created
Surely, there is a way to do it automatically
So can i not make it change automatically
Nope, i was just thinking it could count the number of channel names with tickets
sure, but how is a ticket created
do you have a button, a command or something for it
so in the button callback, calculate the number of tickets, and then use this method to change the status
Could you maybe help me do that, I'm not very good at python
do you know the code which is executed when the button is pressed
There 2 dif bots, do they have to be the same?
One isn't mine the one what i want to change the status on is
so the ticket creator bot is not yours?
nope, it's ticket tool
that would've been good to know earlier
anyways, you can still detect when a ticket is created
Perfect
Yes
do you know how to make an event listener with discord.py/whatever you're using?
Err nope
ok, do you have any code so far?
so you probably defined a bot or client variable?
Yeah, bot
now, you can use the .listen() decorator to listen for an event; ```py
@bot.listen()
async def on_guild_channel_create(channel):
...
that function will be called whenever a channel is created
you can access the guild via channel.guild
and then the text channels of the guild via guild.text_channels
So would it be something like
@bot.listen()
async def on_guild_channel_create(channel):
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="IDk what goes here"))
right
and you'll need to add the code to calculate the number of tickets, and pass that number to the discord.Activity name
Hi , why i dont have anny error and the code dont work?
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", intents=intents)
class automsg(commands.Cog):
def __init__(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")
nombre_mention=len(message.mentions)
if nombre_mention== 0 and message.content.startswith(liste):
await message.channel.send (f"Salut {message.author.mention} ")
if nombre_mention >= 1 and message.content.startswith(liste):
await message.channel.send (f"Salut" + ",".join([mention.mention for mention in message.mentions]))
can i do these 4 functions in one
they are essentially the same but idk how to make them one, so its flexible
Subclass a view
What even is do these 4 functions in one
You can do a for-loop
!e ```py
for i in range(4):
print(i)
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
Use this for the index then keep everything else the same
functions in a for loop?
nvm used url for icon_url 
why does this function only get argument from for loop named i as 3 (last element), how can i fix this
Button callback takes three arguments
self, button obj, interaction
You shouldn't be only getting 3 for i that's kinda weird. You could try enumerating instead of doing i in range(...)
the function only gets i as 3.. somehow
for i, button in enumerate(button_list):
Embed(value=button)
buttons[i].callback = ...
It's an example following where you create the embed
It doesn't change much, it just enumerates the button list
So it gives index and the element itself
I'm not quite sure if it'll fix but try it out first
I mean, it's quite odd your only getting 3 for i as well
bro enumerate and range wont change a thing, this is like saying praying to god will make you a millionaire
cuz enum is range but with 1 more element which u get from it
which would be the actual button in this case
how do i create subcommands for slash commands in pycord?
i tried @suggest.subcommand(name='approve')
but i get this error
discord.errors.ExtensionFailed: Extension 'cogs.modal' raised an error: AttributeError: 'SlashCommand' object has no attribute 'subcommand'
Not even close
Change subcommand to command
discord.errors.ExtensionFailed: Extension 'cogs.modal' raised an error: AttributeError: 'SlashCommand' object has no attribute 'command'
@slash_command(name='suggest')
async def suggest(self, ctx: discord.ApplicationContext):
modal = MyModal()
await ctx.send_modal(modal)
@suggest.command(name='approve')
async def approve(self, ctx, id:int, *, reason=None):
if id is None:
return
chnl = await self.bot.fetch_channel(1068521772191846460)
if chnl is None:
return
msg = await chnl.fetch_message(id)
embed = discord.Embed(
color=discord.Colour.random(),
title='Approved!'
)
await msg.edit(embed = embed)```
Show the code
class MyModal(Modal):
def __init__(self) -> None:
super().__init__(title='Suggest!') #title of the modal up top
self.add_item(
InputText(
label= "Suggestion",
value= "", #sort of like a default
style=discord.InputTextStyle.long, #long/short
)
)
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(color=discord.Color.green())
embed.add_field(name="Suggestion -", value=self.children[0].value, inline=False)
embed.set_author(name=f'{interaction.user.name}#{interaction.user.discriminator}', icon_url=f'{interaction.user.avatar.url}')
chnl = await self.bot.fetch_channel(1068521772191846460)
msg = await chnl.send(embeds=[embed])
await msg.add_reaction('')
await msg.add_reaction('')```
you have to make suggest a group not a slash command
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog_groups.py at master ยท Pycord-Development/pycord
okay ty
it is, the i element of the enum for loop andy gave wouldnt change a thing
im talking SPECIFICALLY about the i element
What are you even talking about
for i, button in range(something)```
andy said that this might change something, but it wouldnt (obviously)
how do i fetch a channel in a modal callback i tried using this py chnl = await ctx.bot.fetch_channel(1068521772191846460) but it doesnt work i get this error TypeError: MyModal.callback() missing 1 required positional argument: 'interaction'
Send the whole error and the full code, not just part of them that's not even relevant
async def callback(self, ctx, interaction: discord.Interaction):
embed = discord.Embed(color=discord.Color.green())
embed.add_field(name="Suggestion -", value=self.children[0].value, inline=False)
embed.set_author(name=f'{interaction.user.name}#{interaction.user.discriminator}', icon_url=f'{interaction.user.avatar.url}')
chnl = await ctx.bot.fetch_channel(1068521772191846460)
msg = await chnl.send(embeds=[embed])
await msg.add_reaction('')
await msg.add_reaction('')```
Ignoring exception in modal <cogs.modal.MyModal object at 0x000001F44F02BED0>:
Traceback (most recent call last):
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: MyModal.callback() missing 1 required positional argument: 'interaction'```
Why do you have both ctx and interaction
Choose one
if i use interaction.bot.fetch_channel it gives another error
THEN SEND THE ERROR
Ignoring exception in modal <cogs.modal.MyModal object at 0x000002EF9D83B810>:
Traceback (most recent call last):
File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "C:\Users\LOKESH\Desktop\Pycord\cogs\modal.py", line 28, in callback
chnl = await interaction.bot.fetch_channel(1068521772191846460)
^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'bot'
I'm going out before causing any trouble
interaction.client
Changing the Position of a role sends an update from EVERY role that got its position adjusted, rate limiting the bot and overall spamming messages I don't want. How can I fix this?
@bot.event
async def on_guild_role_update(before_role, after_role):
embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
if before_role.name != after_role.name:
embed.add_field(name = "Name before", value = before_role.name, inline = False)
embed.add_field(name = "Name after", value = after_role.name, inline = False)
if before_role.color != after_role.color:
embed.add_field(name = "Color before", value = before_role.color, inline = False)
embed.add_field(name = "Color after", value = after_role.color, inline = False)
if before_role.position != after_role.position:
embed.add_field(name = "Position before", value = before_role.position, inline = False)
embed.add_field(name = "Position after", value = after_role.position, inline = False)
if before_role.hoist != after_role.hoist:
embed.add_field(name = "Hoist before", value = before_role.hoist, inline = False)
embed.add_field(name = "Hoist after", value = after_role.hoist, inline = False)
if before_role.permissions != after_role.permissions:
embed.add_field(name = "Permissions before", value = before_role.permissions, inline = False)
embed.add_field(name = "Permissions after", value = after_role.permissions, inline = False)
if before_role.mentionable != after_role.mentionable:
embed.add_field(name = "Mentionable before", value = before_role.mentionable, inline = False)
embed.add_field(name = "Mentionable after", value = after_role.mentionable, inline = False)
embed.set_footer(text = f"Role ID: {after_role.id}")
channel = bot.get_channel(1067413212955426877)
await channel.send(embed = embed)```
You could cache the previous positions somehow, maybe on cog load or in setup hook
When one role is edited, this should theoretically be the one that was actually manually changed
Then modify the cache and compare to it next time to make sure the event hasn't already been handled
Although I wouldn't rely on the API sending through the initial edit first
From my bots this seems to happen most of the time though so should be good
I can live with the other roles appearing (does what code says technically, plus can be useful) but the role position change in in a separate embed from all the other role changes. How can I merge them into one embed?
@bot.event
async def on_guild_role_update(before_role, after_role):
embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
if before_role.name != after_role.name:
embed.add_field(name = "Name changed:", value = f"{before_role.name} -> {after_role.name}", inline = False)
if before_role.color != after_role.color:
embed.add_field(name = "Color changed:", value = f"{before_role.color} -> {after_role.color}", inline = False)
if before_role.position != after_role.position:
embed.add_field(name = "Position changed:", value = f"{before_role.position} -> {after_role.position}", inline = False)
if before_role.hoist != after_role.hoist:
embed.add_field(name = "Hoist changed:", value = f"{before_role.hoist} -> {after_role.hoist}", inline = False)
if before_role.permissions != after_role.permissions:
embed.add_field(name = "Permissions changed:", value = f"{before_role.permissions} -> {after_role.permissions}", inline = False)
if before_role.mentionable != after_role.mentionable:
embed.add_field(name = "Mentionable changed:", value = f"{before_role.mentionable} -> {after_role.mentionable}", inline = False)
embed.set_footer(text = f"Role ID: {after_role.id}")
channel = bot.get_channel(1067413212955426877)
await channel.send(embed = embed)
is there a way i can make the whole code sleep for a specific period of time? and then it should start working again?
Hello guys, yesterday i found out few new things, today i tryed my code, and i need somehow to make if chances to work properly, so code
await interaction.response.send_message(f'Nuplake')
await channel.set_permissions(interaction.user, send_messages = False)
await interaction.channel.send(f'{interaction.user.mention} smeigฤ gerฤ
bankฤ ฤฏ {user.mention} uลพverdamas jo kakarynฤ {minutes} min.')
await asyncio.sleep(minutes)
if chance < 7:
await interaction.response.send_message(f'Nusiplake')
await channel.set_permissions(user, send_messages = False)
await interaction.channel.send(f'{interaction.user.mention} paslydo ir neuลพtaikฤs pliauskos prisiplojo snukiu ฤฏ ลพemฤ. Dabar gulฤs pavฤsyje {minutes} min.')
await asyncio.sleep(minutes)```
If chance > 7: adding permissions to both users, message author and to user which was mentioned , with If chance < 7 all good , how to do it properly
Like the whole program?
@abstract owli think so with asyncio.sleep you can try
Yeah, it should be fine
Better help me with my problem now ๐
so like i wish for it to be off and on every specified time
You can make a attribute for the bot instance then check if it's true
Like
bot.respond_to_cmd = False
await asyncio.sleep(100)
bot.respond_to_cmd = True
Hmmm
hmm that's the issue ๐
i cant get my head
tried searching for module came across scheduler but not quite sure if it serves the purpose
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
so i put the whole bot in there? 
Loop every 1 hour then revert the value
but like it wont run for a hour yea?
it'll loop it but it wont be alive for 1 hour
now like for ex
i have a function print("hello world")
if i loop it, it'll send this every x seconds but i wont the bot to send this for 1 hour continually then sleep for 1 hour
run for x hours
sleep for x hours
repeat
Uh, sooooo, maybe not exactly
yea
How can I edit the message so instead of it saying <Permissions value=0> -> <Permissions value=1024 I can make it simpler and say smth like value = 0 -> value = 1024?
If before_role.permissions != after_role.permissions:
embed.add_field(name = "Permissions changed:", value = f"{before_role.permissions} -> {after_role.permissions}", inline = False)```
Nevermind
Tried smth random and it worked lmao
woah
@tasks.loop(hours=1)
async def meowing():
print("Meow")
This task will
meow
Sleep for 1 hour
Repeat
After running
Changed before_role.permissions to before_role.permissions.value
Kinda close, yeah
Using an f string i can get what i want
yea close but it wont stay on for an hour aaaaa, anyways ty I'll look into some docs maybe it can help. Thanks again cat

That's funny
someone can tell me why i have 0 synced commands ?
what is your code for the sync?
@bot.event
async def on_ready():
print(pyfiglet.figlet_format("BOT ONLINE", font="slant"))
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)```
show your app command code again, kinda need to see that aswell idk why did you delete that
So you know that you are breaking a server rule and are asking for help on that? Now I see the timing, thank you for making your own disclaimer
Hello guys I have created a command handler inside a cog although it is not working. I don't know what I've done wrong. Basically, im trying to make the bot send "Missing role" if a user use the command and has not the role.
Thats the code:
class error(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.command()
async def echo(self, interaction: discord.Interaction, arg):
await interaction.response.send_message(arg)
@echo.error
async def echo_error(self, interaction: discord.Interaction, error):
print("There was an error")
if isinstance(error, commands.MissingAnyRole):
await interaction.response.send_message("Missing Role")
else:
raise error
It seems you are confusing an app command with a prefix command
how could I fix that?
@commands.command() leads me to believe it is a prefix command
However interaction leads to me to believe it is an app command
What is your intention?
yeah its a slash command
not a !command
Should be @app_commands.command() then, once you've from discord import app_commands
you just spawn for these messages man
okay done lemme try, this should fix the error?
Yeah I'm not a regular in the channel, but moderation still occurs
class error(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command()
async def echo(self, interaction: discord.Interaction, arg):
await interaction.response.send_message(arg)
@echo.error
async def echo_error(self, interaction: discord.Interaction, error):
print("There was an error")
if isinstance(error, commands.MissingAnyRole):
await interaction.response.send_message("Missing Role")
else:
raise error
and thats the error I get
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.error' raised an error: TypeError: parameter 'arg' is missing a type annotation in callback 'error.echo'
weird..
I'm experienced in that
type hint arg
arg: str
Also, assuming your error is raised if user is missing some role but you are not checking it in the command?
should I place the error handler inside my cog command?
No
and btw I still get no message while running
class error(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command()
async def echo(self, interaction: discord.Interaction, arg: str):
await interaction.response.send_message(arg)
@echo.error
async def echo_error(self, interaction: discord.Interaction, error):
print("There was an error")
if isinstance(error, commands.MissingAnyRole):
await interaction.response.send_message("Missing Role")
else:
raise error
Yeah, this should work
What does it say? Interaction timed out?
no it just say that I don't have the role
raise MissingRole(item)
discord.app_commands.errors.MissingRole: Role 1054565979394412544 is required to run this command.
Inside your echo_error, do print(type(error)) and see what it says
its weird it do not print anything
its like the cog isnt imported correctly
class error(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command()
async def echo(self, interaction: discord.Interaction, arg: str):
await interaction.response.send_message(arg)
@echo.error
async def echo_error(self, interaction: discord.Interaction, error):
print(type(error))
print("There was an error")
if isinstance(error, commands.MissingAnyRole):
await interaction.response.send_message("Missing Role")
else:
raise error
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(
error(bot),
and here
self.initial_extensions = [
"cogs.test",
"cogs.seb",
"cogs.error"
]
why is there a ,
because after it I have guild_id
I made slow mode on my discord channel but it works only for messages and not commands is there any fix for that?
do anyone have an idea why?
Could you resend the error?
it does not print anything tho except
2023-01-27 19:25:55 ERROR discord.app_commands.tree Ignoring exception in command 'solebox'
Traceback (most recent call last):
File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\commands.py", line 883, in _invoke_with_namespace
if not await self._check_can_run(interaction):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\commands.py", line 1021, in _check_can_run
return await async_all(f(interaction) for f in predicates)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\utils.py", line 672, in async_all
for elem in gen:
File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\commands.py", line 1021, in <genexpr>
return await async_all(f(interaction) for f in predicates)
^^^^^^^^^^^^^^
File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\checks.py", line 232, in predicate
raise MissingRole(item)
discord.app_commands.errors.MissingRole: Role 1054565979394412544 is required to run this command.
this*
So the error is with the solebox command
What happens when you use the echo slash command?
And the error cog is in a module called error.py right?
it isnt a command basically what im trying to do is when the user use the slash command solebox and has not the role a message is sent
yeah inside a folder called cog
Ok, so why don't you make an error handler for it in the solebox cog?
Or you could make a Global one in the error cog with on_application_command_error event
how would I do that?
The same way you're doing it for echo command
I would like to do a global one, that will correspond for every slash commands
you need to make a function somewhere and then do this:
bot.tree.on_error = on_app_command_error # You have to define the on_app_command_error function yourself
okay so holdon I've fixed the problem, now it just doesn't send the message
class error(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command()
@app_commands.checks.has_role(1054565979394412544)
async def echo(self, interaction: discord.Interaction, arg: str):
await interaction.response.send_message(arg)
@echo.error
async def echo_error(self, interaction: discord.Interaction, error):
print(type(error))
print("There was an error")
if isinstance(error, commands.MissingAnyRole):
await interaction.response.send_message("Missing Role")
else:
raise error
<class 'discord.app_commands.errors.MissingRole'>
There was an error
This is what it prints
is commands.MissingAnyRole correct?
import discord
from discord import app_commands
from discord.ext import commands
I import this btw
Why people use cogs when using decorators is so easier
wym?
Using @client.command() is so much easier than using cogs to make comands
cogs combined with extensions give you the ability to hot-reload your code, easily add/remove features, and more neatly organize your project
you still use decorators when using cogs 
Ik, but its different
learning it might be confusing part, but afterwards using it is pretty simple: ```py
main.py
from discord.ext import commands
class MyBot(commands.Bot):
async def setup_hook(self):
await self.load_extension("path.to.my_feature")
bot = MyBot(...)
bot.run(...) py
path/to/my_feature.py
from discord.ext import commands
class MyCog(commands.Cog):
@commands.command(name="my-special-command")
async def my_command(self, ctx): ...
async def setup(bot):
await bot.add_cog(MyCog())```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Any1 can check that error please?
Show your check
I have a syntax error line 7
i removed the () after bot.event i tought it was due to that but no
can i see ur code
@slate swan from discord.ext import commands
That's probably the error
Send us a print of the error
To come back to here, do anyone know please ? Iโve been stuck on this since days haha
How to like put in discord embed (description) x(x litteraly has to stay behind number)random number 1-50.random number 1-50
Should be
if isinstance(error, discord.app_commands.errors.MissingRole):
...
embed = discord.Embed(title="your text", description="your text")
await interaction.response.send_message(embed = embed)
add to this code await interaction.channel.send(f'{interaction.user.mention} megino tvot per veidฤ
{user.mention}')
cuz i cant embed = embed put
There is any way to put embed before await interaction.channel.send ?
Or do embed only for gif
any idea on this error https://pastebin.com/yyNVxqP1 ?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You took more than 3 seconds to respond to an interaction
And how to fix it
By not taking more than 3 seconds to respond to an interaction
Defer & followup then
How i can do it please ;?
await interaction.response.defer()
# do long task that takes more than 3 seconds
await interaction.followup.send("hello world!")
Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py:1089> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 883, in _invoke_with_namespace
if not await self._check_can_run(interaction):
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 1021, in _check_can_run
return await async_all(f(interaction) for f in predicates)
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 674, in async_all
elem = await elem
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\checks.py", line 407, in predicate
raise CommandOnCooldown(bucket, retry_after)
discord.app_commands.errors.CommandOnCooldown: You are on cooldown. Try again in 2.41s
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1091, in wrapper
await self._call(interaction)
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1246, in _call
await self.on_error(interaction, e)
File "d:\Programowanie\discordbot\spotfiyclaim\main.py", line 67, in on_app_command_error
else:
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\webhook\async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
Can i see your code?
Can i send it on pm ?
No
thanks lemme try
@sick birch Man i love you hahah, thanks for the help really. It solved it, by the way as I realized im better doing it now. How do I turn this in order to make a cog that will affect all the commands and not only this command
Your global command handler should be outside of a cog
so I need to put my error handler in the main python file?
@sick birch You checked it ?
await interaction.send(embed = embed);
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'embed' where it is not associated with a value```
any solutions ?
If you want to send embed send it like this
embedVar = discord.Embed(title="Title", description="", color=0x00ff00)
embedVar.add_field(name="", value="", inline=False)
await ctx.response.send_message(embed=embedVar)```
but can i use ctx if im using interactions ?
just change the ctx to interaction
a
and discord to nextcord ?
In embed box should be a gif
so if i put embed = embed
it not gonna work ?
@sick birch So would you help ?
Most likely
Check what?
No offense but that code is really shoddy and I see a lot of blocking
i know i just starting
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
We're not going to help you automate spotify
That's in violation of their terms of service
.
Someone help?
@sick birchAnyone will help me to create custom command were im going to use for my server purpose and time by time adding more features and just keep learning something good in this cruel world
I'm not quite understanding what you're saying
Me or plepuris?
@gentle nova
@sick birchIm trying to code a simple command which have to be like /slap but with penalties, but dont understand why my code struggling to do what i want
I don't either
Since I don't know what your code looks like or what the error is
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Ah, I don't use nextcord, sorry
:/
Role update sends embeds for other roles despite them not changing, I think its because embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow()) isnt in an if but how can i fix this?
@bot.event
async def on_guild_role_update(before_role, after_role):
embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
if before_role.name != after_role.name:
embed.add_field(name = "Name changed:", value = f"{before_role.name} -> {after_role.name}", inline = False)
if before_role.color != after_role.color:
embed.add_field(name = "Color changed:", value = f"{before_role.color} -> {after_role.color}", inline = False)
if before_role.hoist != after_role.hoist:
embed.add_field(name = "Hoist changed:", value = f"{before_role.hoist} -> {after_role.hoist}", inline = False)
if before_role.permissions != after_role.permissions:
embed.add_field(name = "Permissions changed:", value = f"Value = {before_role.permissions.value} -> Value = {after_role.permissions.value}", inline = False)
if before_role.mentionable != after_role.mentionable:
embed.add_field(name = "Mentionable changed:", value = f"{before_role.mentionable} -> {after_role.mentionable}", inline = False)
embed.set_footer(text = f"Role ID: {after_role.id}")
channel = bot.get_channel(1067413212955426877)
await channel.send(embed = embed)```
on_guild_role_update gets invoked for a reason though, maybe an else statement will clear things up
something has changed between the roles which you're not comparing
you can check EVERY attribute, you'll see which one changed
I think I know of a fix but that'll double the amount of lines of code so I just wanted to see if there's one that's more compact
Wait nvm my fix would just repeat the embed description for EVERY change
I'll guess the event is called because someone got a specific role in the guild
(before.members != after.members)
unless that's called on a separate event
I think it might be because the role position gets changed
Youโll seeโฆ itโs an easy fix. Gl!
When you change one role position, it changes all the subsequent ones, so my bot spams those messages too (and gets rate limited grr)
You can just skip the whole message if the position change is the only changeโฆ and I think changes only happen one at a time, nvm, this is not the case as I see in your embed example . so maybe just (positionB != positionA) return
Would fix that
just check for which one has changed it's position out of order
How do I do that?
Can someone help?
are you using nextcord
@upper root mind checking dms?
thx
no problem
@smoky sinew do you have the documentation to manipulate text on pillow
@bot.tree.command(name = "roleedit", description = "Changes the features of a role")
@discord.app_commands.checks.has_permissions(manage_roles = True)
async def roleedit(interaction:discord.Interaction, role: str, name: str = None, color: str = None, hoist: str = None, position: str = None, permissions: str = None, mentionable: str = None):
await role.edit(name = name, color = color, hoist = hoist, position = position, permissions = permissions, mentionable = mentionable)
embed = discord.Embed(title = f"**Edited the role <@&{role.id}**", color = 0xf6ff00)
await interaction.response.send_message(embed = embed)```
Returns `discord.app_commands.errors.CommandInvokeError: Command 'roleedit' raised an exception: AttributeError: 'str' object has no attribute 'edit'` upon execution. Any fixes I can do?
Typehint role: discord.Role
Changed role: str = None to role: discord.Role now I get the error:
Discord.app_commands.errors.CommandInvokeError: Command 'roleedit' raised an exception: TypeError: '<=' not supported between instances of 'NoneType' and 'int'
Can you paste the full traceback?
tbh, I don't see why you would even make such a command, discord's built-in UI is great for this...
2023-01-28 08:38:34 ERROR discord.app_commands.tree Ignoring exception in command 'roleedit'
File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\!Chirpy\Discord Bot Coding\Stardust\main.py", line 552, in roleedit
await role.edit(name = name, color = color, hoist = hoist, position = position, permissions = permissions, mentionable = mentionable)
File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\role.py", line 454, in edit
await self._move(position, reason=reason)
File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\role.py", line 358, in _move
if position <= 0:
^^^^^^^^^^^^^
TypeError: '<=' not supported between instances of 'NoneType' and 'int'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'roleedit' raised an exception: TypeError: '<=' not supported between instances of 'NoneType' and 'int'
I mean yeah, but in my mind its more of an excuse to code things/learn new discord.py code
aight
so your main problem here has to do with datatypes
you're passing most arguments as strings in the command, but in role.edit(...) most arguments need to be specific datatypes (not strings), for example, position needs to be an int
Who would have thought
Would this work out better: async def roleedit(interaction:discord.Interaction, role: discord.Role, name: str = None, color: discord.Color = None, hoist: bool = None, position: int = None, permissions: discord.Permissions = None, mentionable: bool = None):
yes, but you don't see yourself passing a Permissions object when typing out that command, right? xd
Yeah idk how to do the permissions part xd
I hope you're starting to understand the redundancy of this command
it's just not user-friendly
I might just remove the permissions part entirely because doesnt it have to be like the permissions value interger or smth
you'd have to type a shit ton to set that up
(as a member using that command)
sure, you do you
Hey guys
def find_user_info(ctx, user: discord.Member, command):
info = get_user_info(user.id)
if info:
def wrapper(*args, **kwargs):
return command(*args, **kwargs)
else:
def wrapper():
embed = discord.Embed(title="Error",
description="This person has not created an account yet. Start the game with `/start`.",
color=discord.Color.red())
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
await ctx.send(embed=embed)
return wrapper``` i know this code doesn't work but is there a way to do something similar to this?
i use that in most of my commands and i want to make it reusable
id write a check that tries getting the user info, if it succeeds then its assigned as an attribute on ctx, otherwise it raises some custom error that you can catch in a handler: ```py
class NoAccountCreatedError(commands.CheckFailure): ...
def with_account():
async def predicate(ctx):
info = ...
if info is None:
raise NoAccountCreatedError
ctx.account_info = info
return True
return commands.check(predicate)
To use:
@bot.command(...)
@with_account()
async def my_command(ctx):
info = ctx.account_info
...```
oh wow that is very clean
i didnt know you could do that with ctx
dang you can just assign attributes like that?
sure, its one of their few classes that doesnt specify __slots__ so you're free to add new attributes to it
though it is perhaps not a type-safe way to do it, so you might prefer making a function that raises the same error if their account doesnt exist, only difference in error handling would be having to unwrap CommandInvokeError
wait what is the point of class NoAccountCreatedError(commands.CheckFailure):?
