#discord-bots
1 messages · Page 841 of 1
kkk
i like python
Same
!d discord.abc.GuildChannel.overwrites
property overwrites: Dict[Union[Role, Member], PermissionOverwrite]```
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
WHAT HOW DOES THIS NOT HAVE COGS LMAO
Ty
?
the discord.Cogs
!d discord.ext.commands.Bot.cogs
property cogs: Mapping[str, discord.ext.commands.cog.Cog]```
A read-only mapping of cog name to cog.
its a coro
is creating a table for every user that's labelled as their user idea a bad idea?
yes
yes
columns are a thing
make a users table where each user id is
discord.PermissionOverwrite(ctx.author.mention) ? I don’t rlly understand permissions
if i use their user id as a column that means ill also have to have a unique column too
yeah, but isn't that worse?
!d discord.PermissionOverwrite
class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.
Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.
The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.
x == y Checks if two overwrites are equal.
x != y Checks if two overwrites are not equal.
iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
Read this
UNIQUE and PRIMARY KEY are essentially the same
youll have a user table with a user column which must be unique so when inserting make sure its unique
no, because each user would need multiple columns
i like UNIQUE better imo
and?
only majoir diff between UNIQUE and PRIMARY KEY is that PRIMARY KEY doesn't accept NULL values
idk how a database finds the data, it seems like it would be slower
# User table
| user_id | name|
123456 pepe
because i would need to use WHERE user_id = whatever
and there can only be one PRIMARY KEY constraint in a table
and then if each user has like 1k columns
it isn't slow
f"SELECT * FROM usertable WHERE user_id = {ctx.author.id};"
!sql-fstrings
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
its not taking user input
youre fine
no need for placeholders as you cant inject anything to it
Bad practice is a bad practice regardless
how is that bad practice?
Because it doesn't sanitise the input at all
^^^
🤔 how does that matter, you're still putting in data to the database
You should still parameterise the ID
thats not by a user?
thats generated by discord
you can practice it but its kinda overkill and unnecessary
is there a way i can make a command where it will show images of a specific thing from google or some other image site?
like if i wanted it to just show pictures of olivia rodrigo
sorry if i sound dumb i’m kinda new to all this
then youll need to webscrape or if they have a restful api use it
ooh alright ||pretends to know what you’re talking about and searches it up on the internet||
🧐
REST api
same thing
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
ctx.guild.me: discord.PermissionOverwrite(read_messages=True)
}
await ctx.guild.create_text_channel('test', overwrites=overwrites)
its called a REST api or a restful api
Not working
RESTful
Representational State Transfer 🗿
ful
you know what i mean, so it doesnt matter
how can i make a command that will add a picture to a list of choices? i have a command ?img and i want people to be able to add images to the list of images that are already there (the code chooses a random image)
my god am i dumb, but yeah instead of an api this would make things easier
so ppl can submit pics for the command
probably made a bunch of mistakes but that would be the table and select, second one is better?
How so, practising in a bad way will end up making bad habits; bad habits die hard. If your code base has a lot of non parameterised queries that take in dynamic values its gonna end up biting you in the ass, I'm sure you'd be more likely to mistake when and where to use it, or to use it at all. And I'm also sure some people will be looking back at their previous queries as a point of reference. Disastrous overall don't you think?
im gonna try and figure it out myself but if anyone could help i’d appreciate it :)
also in #🤡help-banana so it doesn’t flood chat if you’d like

basically i would like to make a “submit picture” command so users can add pictures to the image command
ctx.guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True)
What do I replace .me to in order for author to have permissions
idk how to explain it well
🤔 what
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True)
}```
I can’t seem to make .me the command user
the image command shows one random picture from a set of random choices and i want to make a command that lets users submit pictures of their own to the image command
that makes the most sense
oh you're looking for help
yeah
so if a user submits a picture, it will show up (at some point) when i do ?img
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True)
}
await ctx.guild.create_text_channel('test', overwrites=overwrites)``` how do I make it under certain categorie
hi so I have a create role command and I'm wondering how I could make all the roles i create, have display differently toggled on
this is what I have rn
# createroll command
@client.command(aliases=['cr'])
@commands.has_permissions(manage_roles=True)
async def createrole(ctx, *, role:str = None):
guild = ctx.guild
perms = discord.Permissions(permissions=0)
await guild.create_role(name=role, permissions=perms)
await ctx.send(f'`{role}` was created')
Can't agree more, I always look in my code for reference
imagine having a reference of bad habits code you will be trapped in this loop forever 
Bad habits die hard
Or don't die at all 
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True)
}
await ctx.guild.create_text_channel('test', overwrites=overwrites)``` how do I make it under certain categorie
get a channel, with the category id, then make the channel in the category
category = bot.get_channel(category_id)
await category.create_text_channel()
Aw Andy... Disnake ruining it's good progress... https://guide.disnake.dev/prerequisites/migrating-from-dpy
import disnake as discord 😔
smh how could they
Guide website looks better than docs
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True )
}
category = guild.get_channel(944748748117012560)
await category.create_text_channel('test', overwrites=overwrites)```
yes, assuming you changed guild for ctx.guild
They did update the site, but the fact they tagged with Menudocs now is just :(
The only thing they changed was the toolbar area
I'd expect something users would end up looking at 90% of the time to be at least appealing
Yeah but they literally did ctrl+c + ctrl+v on this site
Error
I think I’ve used await wrong
My bot is not reacting
No Commands are working
which
Yes
I'll have to learn next.js or vue to up my docs game 😔
Just use css
Message content intent?
no
do you have an event anywhere
@bot.event
async def on_message(message):
...```
only 2
@hushed field
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True )
}
category = bot.get_channel(944748748117012560)
await category.create_te
Await outside function why tho
fix your indentation
Kk
do me favor
at the top of your code, import traceback
and then?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Mb
await can’t be used outside an async function
then in your on_command_error, after the isinstance add the following:
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)```
The indentation is off
🗿
🗿
fix indentation
Ok
and import sys
Me?
yes
you
Still same error xD
What does this do?
He prolly have an issue with on_message or his command handler
ok, whats the error
no on_message event
bruh read the error
does he not have an on_message or process commands?
i did now but nothing showed up
just prints out your error in a command handler instead of eating them
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
he doesnt have a on_message event
nothing
what did you do
...
Seems like he want to print the error
Though it's easy just to raise error 
await ctx.send(embed=em) goes INSIDE your if statement
yeah you don’t need all this builtin shit
category = ctx.guild.get_channel(CATEGORY_ID)
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True )
}
await category.create_text_channel('test', overwrites=overwrites)
bro
if you just print out error your going to get a small 1 line error, hes now getting full tracebacks for debugging
@hushed field
idk just send me the code
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Cooldown!", description=f"Try again in {error.retry_after:.2f}s.", color=0x9208ea,
timestamp=datetime.utcnow())
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
await ctx.send(embed=em)
There is something called logging module
category = ctx.guild.get_channel(CATEGORY_ID) goes inside the command
Where abouts
if hes having indentation errors how do you think logging will go for him
IN the command
indentation errors are brought up by VSCode
That doesn’t need some crazy dunder method shit
mate what
the line await ctx.send(embed=em) goes INSIDE the if isinstance statement
if you dont know what that means or how to do it, learn python
.
my english is
bad just edit it
no

@hushed field it works but how do I make it so only 1 channel created at a time
?
right?
What
help me
what do you mean? how many channels does it make
Did you triggered the cooldown? 
well lets start with the basics
im assuming the bot comes online and the prefix is ?. i am also assuming the bot can see the channel
yes bot haves all perms
and prefix is ?
does the gen command work?
no command work
import traceback,sys
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Cooldown!", description=f"Try again in {error.retry_after:.2f}s.", color=0x9208ea,
timestamp=datetime.utcnow())
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
await ctx.send(embed=em)
Put code here, click save, send link - https://mystb.in/
i try this first
then yes
and the traceback:Traceback (most recent call last):
File "c:/Users/ad/Desktop/python-exerise/Python/Python-progect/jjj.py", line 2, in <module>
@bot.event
NameError: name 'bot' is not defined
but why is it the same thing
@slate swan you have to process the commands in an on_message listener
from my embed
you use VS Code right?
yes
@bot.event
async def on_message(message):
…
await bot.process_commands(message)
how many times am i going to tell you, he doesnt have a on_message event
then make one lmfao
what have that to do with his problem
the bot isn’t responding to commands
^
Then he should fix the commands not doing something amateurish in on_message 
for what?
I guess I’m misunderstanding
You probably do

Probably I misunderstood too, since I don't get it if the cooldown it doesn't work or the whole command
the whole command
All Commands not response
It should
Vestige: ?help
Bot: Help: 1, 2, 3
But now:
Vestige: ?help
Bot:
idfk how on_command_error helps with the bot not responding to ANY command. But, again, I could be misunderstanding this whole thing
Before it worked?
yes
but today not more
I want to do that when you do !close it deletes current channel your on but I’m not sure how to get channel id?
idk if this helps
Ok
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
I know how to delete
It’s just getting id
There is also TextChannel.delete and CategoryChannel.delete but it seems like they are the same
Will it delete the channel your on
ctx.channel.id should be able to get the current channels ID
If u do channel.delete my guess is that it will delete the current channel you type the command without a specific id
do anyone know how to solve this?
Are they installed
isn't it commands
and/or is the right interpreter selected
not command
Import commands
Yes
this?
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
ok
@bot.command()
async def close(ctx, channel_id: int):
channel = client.get_channel(channel_id)
await channel.delete()
await ctx.send("Successfully deleted the channel!")```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I think i've finally got my tables saved to a database 😓
How i can make a Public Int?
Example in C#
public static int number = 1;
?
global variable
can you give me example please
Python doesn’t have access modifiers
Wait I got an idea
mine work without channeld Id
the convention is showing that something is private is to add an underscore before the name
i know how to do it on the main.py but no in cogs
should I replace ctx.send to self.send?
it's the same thing
But with some addons
!e
x = 10
def main():
y = 15
print(y)
@slim ibex :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | NameError: name 'y' is not defined
Here, X is global (public) and y is local
My channel names become your discord id so that’s how I’ll delete (300 iq)
is there an official coding/python jargon dictionary?
Just use api
No you don’t send on the instance
!d import discord
so do I keep ctx?
yes
alr
i dont understand this
but in class, self is the first param for methods
unless it’s a class or static method
hmm.. what about guild = client.get_guild(ctx.guild.id)
i get it thanks
Here you need self before client
global x
🗿
Since client is likely not a parameter of your command function, and it shouldn’t
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
It's free real estate
💀
@bot.command()
async def close(ctx):
channel = ctx.message.author.name
await channel.delete()
await ctx.send("Successfully deleted the channel!")```
When you get 300iq buy python says otherwise
What
lmfao dude
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Check this out
💀
Bro
You have no idea what you're doing
Holy shit u didn’t have to do him like that
I'm already losing brain cells
💀💀💀💀
So this monstrosity is broken
Ofc
LOL
bor discord broke
So basically ur channel is the author name
and you want to delete???


Yes
So rn channel name is alexlol
Lmao
That's like fatality
I swear he just sees
Alex lol = resources
Like it’s bullying at this point
@final iron pls stop bullying me???🥺🥺🥺🥺
Now the whole server is bullying me
Not fair bro 😢😢😢😢😢

Tbh I’ve never used resources bc I get 15 minutes in and I get bored
Then read docs
Still boring but well
Read the source code, you'll have fun for 10 minutes trying to figure out whatever the hell danny was doing
Then spend the rest crying
Danny did a good job since his main job is not even programming kekw
O lol
He's a doctor
Like fr, finding enough time to work at such library is insane
The channel is the users id
@bot.command()
async def close(ctx):
channel = ctx.message.author.name
await channel.delete()
await ctx.send("Successfully deleted the channel!")
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.

with self, ctx
@hoary cargo I hope both your pillows are warm
and without ctx
you can't do that to me
Why would you even remove ctx
i was trying if it worked like that
but didn't
same error
you need context
context is the attr that has send which youre using which it should be the second argument since the first is always self to access the class
guild = self.client.get_guild(ctx.guild.id)
Is this correct right?
if client is your bot yes
@bot.command()
async def close(ctx):
await channel.delete()
await ctx.send("Successfully deleted the channel!")
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True )
}
category = ctx.guild.get_channel(944748748117012560)
await category.create_text_channel(f'{ctx.message.author.name}', overwrites=overwrites)
await ctx.reply("channel is created")
Plan: deletes the channel you say the command !close on
await ctx.channel.delete() if you mean the current channel
its a coro lol
They have already awaited it, just failed to get the right channel object,( if you notice their 3rd line)
what do i type here
to run it
yeah but if youre gonna show how its done atleast do me the favor and await it
Also it's suggested to implement some check on the command , else anyone would be able do delete all the channels
Alright
Well all channels are on 1 categorie
run what and youre using the windows power shell?
how i can use for this a global int
yes cuz when i open it it autocloses
wdym a global int?
like
global genMax
global genCooldown
Yes but I don’t wanna have to specify channel
then theres probably an error
and then i can use it
if you're double-clicking the file to launch it, this isn't a bug. Python files launched this way will open their own window, but won't automatically keep it open when the script finishes.
You can open a console and run the script from there, like this:
- open File Explorer to the directory where you have the file
- in the address bar at the top, type cmd or PowerShell and press Enter to launch a command line in that directory
- In the newly opened window, type python <filename>.py (where <filename> is the name of your Python file)
3a) py instead of python may also work and is recommended whenever possible. - this will launch it in a window that you can control.
Holdon, what? You are getting the guild, from the id of the guild you already have
i was told to do that
they should know at least this, that it should be awaited, otherwise it's just spoonfeed and they don't know what they doing
@slate swan actually I got better idea I’ll just make it so it auto closes after 30m
You can get the category using Bot.get_channel(category id) and loop it's channel using CategoryChannel.channels And delete them.
wat do i type when im in powershell
L o L
and if they didnt know it would raise a big tracemalloc error
@slate swan
.
@slate swan
why ping me
xD
that you read xd and maybe help
It’s like ticket system so I don’t want them deleting other peoples tickets
🥴
Please its important for me
you want all cooldows to be the same?
i am making a setcooldown command
but its not working
you can either cache what channels belongs to the user, or name it as the user id and then use discord.utils.get to get that channel
and i think maybe the int is not global is the problem
!botvar
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!
I do, you are too lazy to read.
not sure how it didnt pop to my head lol
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True )
}
category = ctx.guild.get_channel(944748748117012560)
await category.create_text_channel(f'{ctx.message.author.name}', overwrites=overwrites)
await ctx.reply("channel is created")
time.sleep(0.10)
ctx.channel.delete()```
format it atleast
and time isnt async
Don't use time, use asyncio.sleep instead
use .sleep from asyncio
Which is?
so you wont block your whole bot and disconnect it
await asyncio.sleep(0.10)
it just sleeps on that coroutine
i readed it rn but i dont understand it :C
it wont hence the time of sleep but great amount of times will
slee 👁️ 👁️
Also how long is 0.10
10s?
prefi?
0.1 seconds
no
Ok
1.0 is one second time units lol
Damn
can anyone help me?
the set cooldown is not working
youve been told already.
BRO I dont understand that shit
im not a bro. and its just a global variable bound to your bot?
is genMax and genCooldown supposed to be dynanmic, if so it's not gonna work
!d discord.utils.get , now if you want to delete it with the close command you may just use this with Guild.text_channels as the iterable and name=Context.author.name as the attribute identity
Where Guild and Context represent there current objects.
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
what you mean dynamic?
dynanmic😖
nani
The decorators on run-time only "register" the commands, thus whatever the cooldown was at first would be the cooldown used forever
If you were to change the value of them, it wouldn't do a single thing
Suggested them botvars but that's not what I asked 🏃
That wouldn't even work, again as I said above
!d discord.ext.commands.Command.update could work, if you pass in cooldown
update(**kwargs)```
Updates [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") instance with updated attribute.
This works similarly to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator in terms of parameters in that they are passed to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or subclass constructors, sans the name and callback.
not us, we are not allowed to spoonfeed here.
or are we? ;)
Andy, command handler when?
do i put it inside bot.command() ?
🥴
t fook
@bot.command()
async def start(ctx):
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True )
}
category = ctx.guild.get_channel(944748748117012560)
await category.create_text_channel(f'{ctx.message.author.name}', overwrites=overwrites)
await ctx.reply("channel is created")
asyncio.sleep(30.0)
ctx.channel.delete()``` @slate swan will channel created delete in 30s
cannot relate, i just give people hints with Objects and docs until someone gets annoying and ping me 100times
.sleep is a coro it will never sleep lol
Yea surely
But await it as zilo said
i just press the block button😖
What do you mean
wow no one answered my question
delete is a coro🥴
@slate swan what did i told you he forgot to await it😟
delete() method is a coroutine.
O yea
So will I just remove ()
bro
you await it like any coroutine.
I’m tired
Sorry
Ifs 3am so ye
await ctx.channel.delete()
```😱
go to sleep🙃
Pls be joke
Yea I’m really tired
no joke
How do I not notice that
you will when that big o tracemalloc error comes
Can someone help me with something
Won't rin have one?
Please
dont ask to ask just say
Just ask the question
🎉 true, I just assume that people read the docs before using the methods.
yes sure, that's the aim of this channel.
guess people dont😖
What type of commands
I feel an urge to !resources again
It’s 3am give me a break
message commands
or is it gonna be app command only?
This is not the same thing i am trying it with @commands.cooldown(genMax, genCooldown, commands.BucketType.user)
but he with text or smh
it's 5 am here and still
Is there any one here that knows how to make like where ur bot asks you questions from running the command in the discord server and then saves the info on the server and also sends you the results on the dm?
The goal of Rin is to be as native as possible, if the demand is there I will maybe make chat commands, it’s easy as hell I’ve already made chat commands for Lefi
You use the update method which andy sent inside the cooldown command to set a new value for cooldowns.
global genCooldown
genCooldown += int(arg)
It’s my time to shine
i use this
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
😈😈😈😈😈👹👺👺👺
@hoary cargo damn this feels good
can someone help me
but how i can update it for all i mean that the value get updated for cooldown too
You need to help them
Oh cool, was just wondering how different is it gonna be than discord.py's handler ,
Cause everything else seems smarter 👌
what do i type here
That’s the whole point of this channel
if you're double-clicking the file to launch it, this isn't a bug. Python files launched this way will open their own window, but won't automatically keep it open when the script finishes.
You can open a console and run the script from there, like this:
- open File Explorer to the directory where you have the file
- in the address bar at the top, type cmd or PowerShell and press Enter to launch a command line in that directory
- In the newly opened window, type python <filename>.py (where <filename> is the name of your Python file)
3a) py instead of python may also work and is recommended whenever possible. - this will launch it in a window that you can control.
Imma have a look at lefi's
Type python <filename> to run the file you want
Lefi was pretty much discord.py type but I did all the internals cleaner
make sure python is added to path
If Rin ever does get message commands it will be different
Py delete win32
the python file or the file name
To run file on windows: python filename.py
Rin 1.0.0v ETA by the end of this month. Be there or be square 😼
???
How i can update a Int for all
My Problem
!cooldown
Bot: 5 Seconds
--------------------
!setcooldown 10
Bot: 5 Seconds
The Values:
genMax = 1 # Max Gens too get the Cooldown
genCooldown = 60 # Cooldown after Max Gens (in Seconds)
Code to update the Cooldown value
@bot.command()
async def setcooldown(ctx, arg):
if ctx.message.author.guild_permissions.administrator:
global genCooldown
genCooldown += int(arg)
embed = discord.Embed(title="Counter", description="", color=0x9208ea, )
embed.description = "Current Cooldown to: " + str(genCooldown)
await ctx.send(embed=embed)
else:
print("failed")
Why this happening??
The Cooldown Code @commands.cooldown(genMax, genCooldown, commands.BucketType.user)
Now that I’ve actually committed I’m gonna kick this up high gear and do work 😔
ayo
Assuming you want to run a file named bot.py , you would just do python bot.py ( or py/python3 instead of python ) depending on your installation
Wow i mean i kinda did it but its a bit too long of a code
i want a more shorter one
look at dms
I have to make like 40 attrs for the user class 😔
def run(self) -> None:
try:
for filename in os.listdir("./src/cogs"):
if filename.endswith(".py") and not filename.startswith("_"):
self.load_extension(f"src.cogs.{filename[:-3]}")
log.info("Cogs loaded successfully!")
except FileNotFoundError:
log.error("A cog or multiple cogs failed to load.")
super().run(token="")
i think im fucking some shit up somehow because everytime I run my bot, it runs the except block ):
I need help for Windows directories, some letters aren't detected and causes errors
Like the D and the S
I have to make attrs for all of these
😔
@pliant gulch Is there some way I can do it dynamically and not have to hardcode all of it?
Idk why it doesn't works everywhere
"For all of these"
The screen shot:
from disnake.ext.commands import Cog, slash_command, Context
from ..utils.converters import TimeConverter # unused import don't worry bout it
class Moderation(Cog, name="Moderation"):
def __init__(self, bot):
self.bot = bot
@slash_command(name="kick", description="Kick a user from the server.")
async def kick(self, ctx: Context):
"""
Kick a user from the server.
Usage:
`/kick @user`
Parameters:
ctx: The context of the command.
"""
await ctx.send("TESTING")
def setup(bot):
bot.add_cog(Moderation(bot))
this is me cog
I had to zoom so far out to get them all
Send the code i'll make a sharp one
Just convert the json to an object with attritbutes
I have this in my own bot as well to convert yaml to an object:
def _obj_dic(d: dict):
top = type('new', (object,), d)
seqs = tuple, list, set, frozenset
for i, j in d.items():
if isinstance(j, dict):
setattr(top, i, _obj_dic(j))
elif isinstance(j, seqs):
setattr(top, i,
type(j)(_obj_dic(sj) if isinstance(sj, dict) else sj for sj in j))
else:
setattr(top, i, j)
return top
pls help
!e ```py
def _obj_dic(d: dict):
top = type('new', (object,), d)
seqs = tuple, list, set, frozenset
for i, j in d.items():
if isinstance(j, dict):
setattr(top, i, _obj_dic(j))
elif isinstance(j, seqs):
setattr(top, i,
type(j)(_obj_dic(sj) if isinstance(sj, dict) else sj for sj in j))
else:
setattr(top, i, j)
return top
test = _obj_dic({"yes": "no", "no": "yes"})
print(test.yes)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
no
So it just creates an attr with the key name?
Can anyone help me in #help-pineapple
Here's the code (too long to send directly so sending a codesnap pic)
"fllaten"?
oh spelling error
cv2 and discord bots is just asking for trouble.
At least have some kind of async loop task.
time.sleep(5) i give up
Oh ok
xD
again this error
self.__dict__.update(self.data)
Please look into the difference between, async and sync code.
Ok
What does that do?
Updates the classes namespace with the stuff inside of self.data, that being the raw dict
Is there any way I can disregard some of the data in the raw dict?
dict comp
So this?
Not exactly of course
I'll have to change the code
eh
ayone help
But it's a json file 
you could use that I guess, but it's kind of weird lmao
Could you show a different example then?
https://github.com/an-dyy/Rin/blob/master/rin/models/base.py heres my base class for rin, I use this to turn raw dicts into classes
!e
list_ = [1]
print(list_[1])
@final iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: list index out of range
See the issue?
hmso how i get the users that reacted to the rection so that random can choose one of them
🧍
:incoming_envelope: :ok_hand: applied mute to @jade tartan until <t:1645328091:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 125 newlines in 10s).

@jade tartan Wait a sec, mods sometimes will unmute.
Interesting
!paste use this next time for long code.
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.
:incoming_envelope: :ok_hand: pardoned infraction mute for @jade tartan.
Interesting
Ohh thank you sorry i didnt know about this
npnp
It's hard to understand at first but then it gets easier
What is that error i tried to read it but it was very quick :3
Basically my best attempt at a swiss-knife class builder
no
Could not convert "user" into UnambiguousMember or UnambiguousUser.
User "944796891873423390" not found.
https://paste.pythondiscord.com/zosanawoqi i would like to make this work and also much shorter
I'll give it a try I guess
Ohh yeah, saw it before, was curious.
It only works with python-attrs btw
What is that?
I'll try and make it as short as possible
A library?
Yea, like dataclasses
!pypi attr
Thanks tho
in a DRY way
I appreicated it
Why is DRY capitalized
Wdym by work? It doesn't work?
!src unmute
Prematurely end the active mute infraction for the user.
Prematurely end the active mute infraction for the user.
jinx
:(
Like it says that all these catagories is undefined
our repo is free for you to peruse
like sixteen is undefined
Well why didn't you define it when you put in sixteen?
oh while i'm here
You're using a variable 
anyone experience vscode not running their bot when using the launch.json configuration? but using python -m bot works perfectly fine?
File "/Users/mina/projects/bot/bot/api.py", line 68, in maybe_raise_for_status
raise ResponseCodeError(response=response, response_json=response_json)
bot.api.ResponseCodeError: Status: 401 Response: {'detail': 'Invalid token header. Token string should not contain spaces.'}```
it's very strange, started today
python -m bot works no issue
pycharm run as module config works no issue
it's just using the run config in vsc that does this
Huh? I assume your token doesn't have any spaces..
yeah it doesn't
and it runs perfectly fine when doing python -m bot
same interpreter, etc.
it's a MYSTERY
So it's just an issue on vsc?
for that mute cmd do i need to do download any module
yup
for that
this is the launch config
{
"configurations": [
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "bot"
}
]
}```
I think @unkempt canyon only uses the base discord.py
I don't really use vscode anymore :3
Have you asked it in #editors-ides? I will search it online..
It does since Client is the base class. It uses Bot though.
i gave up on it for now since i can just run in terminal
Ohh right ok so for that to work i need to change the from bot.... to from client?
I assume you mean when you hit the ▶️ button in vscode?
I'm sorry i'm not following? It's a class, you can do it with either one, but using bot is much easier.
You certain there aren't any trailing white spaces in the yaml file?
@pliant gulch How does your base model account for type hints though?
I mean it as a lot of Any lol
.env file, but yes positive
let me show you a screenshot of what i mean by that
and if there were, why would it work when running in terminal?
@cloud dawn
From the types passed, doesn't work with many things, so refactor 2 is coming soon
no wait i'm dumb
Is this how it works?
Alright. How would you make it return your own custom objects though
hmm
You add the custom object to the type
That's what I'm doing at least,
And for complex types you use BaseModel.property
But you just copy pasted the entire file..?
Currently reading this, tbf this has some weird exceptions and rules... -> https://code.visualstudio.com/docs/python/debugging
Huii huii huiii
which i pasted into my .env while i already had the debugger running
and hitting the green refresh button was fine

but it wasn't fine when i tried to run it again
It wasn't updated yet.. xD
ah
interesting tho that running from terminal still worked
so no end of line # comments are allowed i suppose
or at least, not consistently
Hmm maby the env got cached by vscode since the vscode was still running but from command line would open a new instance of python.
right
well
idk the inner workings or reasons
but thanks lol
i was going crazy
can i put comments as new lines in .env files?
let's try
Hahaha, i too have had these moments, think everyone has at some point.
it appears i can
Top comments work yeah, did you put the token in a string? "TOKEN"?
ohh i just need the mute command then
to copy paste it with the specific module
!src mute
Temporarily mute a user for the given reason and duration.
Maby
token="XXXXXXX" #comment
The issue with copying @unkempt canyon his source code is that you need to understand Python since a lot of the commands use functions, classes, converters that they've made on their own. And those converters have other functions again etc..
no, just TOKEN=XXXX
comment was on a different line
I recommend not copying but to get the general idea of the command and try to make it work the same.
BOT_API_KEY=XXX # comment
hey
Hmm okay, well nice of you to check out Discord bots :3
Al tough it is quite a mess right now with the libraries, what have you chosen?
is there any way to get a bot's prefix to be slash commands?
well yes there's a way
but what is it
You mean you want to make a slash command in general?
this is actually @unkempt canyon i'm working on
so dpy
Well first you gotta add application command to the scope so that prob means you gotta re invite the bot.
ty for the help & sanity checks :3
Ohhh, i can imagine the setup... lol
i have made a couple teeny tiny PRs to bot
i added application command already to scope
how to make subcommands?
.fact cat``` etc
Well i do but i dont understand it when its done that way
!d discord.ext.commands.Group.command
!d disnake.ext.commands.group they are called groups.
@disnake.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Group "disnake.ext.commands.Group").
This is similar to the [`command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.command "disnake.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Group "disnake.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
oh thats the one i wanbted
oh so we defaulting to disnake now when searching the docs
🗿
Discord, Nextcord use whatever you prefer. I use this since this is the one i got open.
ohh so that means the definition of sixteen is suppose to go with the async function?
As long as the libraries look alike i will just send whatever i got open in my tab rn 😂
Well you need to define it somehow, as i can see it is a role, best is to then use an ID.
Nah panda specified disnake
I'm going to sleep now, it's late.. @jade tartan, Robin has arrived, he knows all.
Stt
robin is a genius
oh damn
ah yes the 🗿 is spreading
Yeah see he even got the yellow tag thingie so he can solve.
I popped in just to check but I suppose I’ll be staying a while hehe
oh
well that's nice
do you think you can answer my question i had to Pandabweer
sure can you link it i'll take a peek
ok
ayo robin
help a man rq
!src unmute
Prematurely end the active mute infraction for the user.
let me take a peek
Oh you want the prefix itself to be /?
I mean it's doable but it's gonna make it very difficult for people to use your bot
oh
He means an application command not setting the actual prefix to '/'
Everyone wants to be helped by a helper, so not surprising 👀
so, just a regular old slash command?
Facts -> #discord-bots message
my logger ain't logging info level stuff 😢
yeah
Imagine using a logger smh
So you're just looking for slash commands? that's easy, just use one of the forks if you aren't already and problem solved
You don't?
depends on the type of logger
what does that mean
also umm
@slash_command(name="kick", description="Kick a user from the server.")
async def kick(self, ctx: Context):
...
TypeError: <class 'disnake.ext.commands.context.Context'> is not a valid parameter annotation
are you currently using discord.py?
Nope
e.g
import discord
or anything similar
yeah
can anyone help how can i make that my bot do not win the giveaway
what did you mean by "forks" though
you can use an if statement to check if its the bot
Unfortunately discord.py does not support slash commands so you'll either have to implement slash commands yourself (i would be happy to explain how) OR use a fork which does it for you
ok
"forking" is a github term where someone can make a copy of a github repository, and change things and republish it
oh
del users[self.bot.user]
anyone help?
Bot auto reacts since that's the first reaction.
I think the most prominent discord.py fork is disnake though at this point there's like 20 so you might wanna give all of them a try and see which implementation of the new features you like best and take it from there
oo del keyword. don't see that a lot
ok
It's inter not ctx.
what about implementing them myself?
oh ok💀
you could with relative ease
I'd be glad to tell you how I did it if you'd like
!d disnake.Interaction would it be this @cloud dawn
class disnake.Interaction```
A base class representing a user-initiated Discord interaction.
An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.
New in version 2.0.
inter: ApplicationCommandInteraction to be exact.
oh that one
ok sure
Seemed like the fastest way in his case without doing anything too difficult.
ok i will try
Alright, the hardest part is honestly registering the slash command itself. It's a one and done thing so what you'd wanna do is send a HTTP POST request to the discord API registering the slash command, and you can use on_interaction to handle the responses. You might also wanna make a decorator that automatically calls functions based on their names and slash command names
@slash_command
async def slash_command_name(interaction: discord.Interaction):
# process stuff here
https://paste.pythondiscord.com/owalalokiy someone help me?
@slash_command()
kek finally
ah yes Cache
🥳
Unbelievable though, MESSAGE_CREATE's member object doesn't give user smh
i was going to unironically type everything out in Cache()
ok i'll try it
@cloud dawn
Ok I'm taking back the v1.0.0 ETA I hate this already
😔 I did that for like 1 hour and I'm already tired of it
!paste Could you send the command code
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.
you want me to show you all the code?
Did you make it shorter?
@cloud dawn here is the code
alright so how is the slash command registered via HTTP POST
u spelled token wrong
I might not be reading one part of what you said
Yeah inside a paste i can't copy this.
so forgive me if that's the case
is it possible to move a bot to another bot? like combine multiple bots
So imagine sending a text to a friend, that is a POST request from you, he then REQUESTS the data from a database if there is a new message.
Use the same token in different codes?
ohh
Rip rate limits
like if i have 2 bots but want to make them just one
I hope that bot doesn't have any events 
Idk
from my current understanding every bot is like a permanent unchangeable thing
Bruh ikr
Just move the code uh, you are wasting time asking
i don't get it, if rate limits are bad how can bots run in like millions of servers
Verification
If the bot is verified then it bypasses the rate limits
ok
import requests
url = "https://discord.com/api/v8/applications/<my_application_id>/commands"
# This is an example CHAT_INPUT or Slash Command, with a type of 1
json = {
"name": "blep",
"type": 1,
"description": "Send a random adorable animal photo",
"options": [
{
"name": "animal",
"description": "The type of animal",
"type": 3,
"required": True,
"choices": [
{
"name": "Dog",
"value": "animal_dog"
},
{
"name": "Cat",
"value": "animal_cat"
},
{
"name": "Penguin",
"value": "animal_penguin"
}
]
},
{
"name": "only_smol",
"description": "Whether to show only baby animals",
"type": 5,
"required": False
}
]
}
# For authorization, you can use either your bot token
headers = {
"Authorization": "Bot <my_bot_token>"
}
# or a client credentials token for your app with the applications.commands.update scope
headers = {
"Authorization": "Bearer <my_credentials_token>"
}
r = requests.post(url, headers=headers, json=json)
``` This is a really raw requests, this is what you send but disnake has made it nice and readable for you. Discord parses this json data and put it as a command :)
Eh? Doesn't really work like that.
Okay
requests
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
oh really?
every where i read about rate limits it seems to have different info jfl
Love your pfp
is that the on_interaction() command robin was talking about?
Read official statements
Which panda just sent
yo thanks
are there places i can put discord bots where it would become popular?
top.gg and discord bot list
We don't really, give "advice" like that here.
After Verification*
Bigger bots get a different ratelimit
Compared to that of bots in less servers
yeah
Plus, ratelimits have buckets
The ones you can put on your head.
As long as regular bot's don't go over the 50/1s global ratelimit and handle their buckets properly your good
if you've worked with cooldowns in discord.py it's similar as well, it also has buckets like andy is describing
Loool
https://paste.pythondiscord.com/owalalokiy someone help me?
Water bucket?
Does it work?
O WHERE CAN I GET ONE?
🪣
thank you panda guru
🤔
mustve been the wind
All jokes aside the bucket system is amazing, and if you are interested i recommend checking this out. To get to know more about how Discord rate limiting works 
You can really imagine discord's buckets as an actual bucket with water, this water is separated from the main source of water, thus has different amount of usages etc
different buckets with different items as well
each bucket has a different amount of water in it if that helps you understand
Depends on how you decide to hash your bucket identifiers though, that part could get messy if you don't do it properly
Is it against TOS to attempt to bypass the rate limit
Yea most likely
Ok
yep
don't even attempt it, they're there for a reason
Rin's ratelimiter handles bucket depletion concurrently 😼 We don't use Locks unlike discord.py instead we have a Semaphore that uses X-Ratelimit-Limit as the thread count
I mean is it illegal to bypass the speed limit on your highway? 👀
If you live in germany it doesn't count.
🗿
I live in
but people do it anyway then complain about it
or die
Usually the first one
if it isnt the first one discord gonna have to answer some tough questions
Wait how can u even bypass the ratelimit lol
You could bypass ratelimit but you'd need to master socket module and some udp networking first.
well rule 5 so let's not talk about that lmao
how do people even generate >50 requests/second worth of activity from bots that are in <100 servers
Most likely a ***** or a ***
panda dangerous waters
You can't really bypass it with the same bot token anyways
you don't
unless you're doing it deliberately
They request discord to increase their ratelimits
Purge commands get close.
spam bot on replit sad noises
possible but not really common
Purge command counts as a 1 request per 100 messages or under
Like i got a bot, and if it's getting ratelimited frequently for sending messages, I can contact support to increase the ratelimit
Plus, you also have bucket handling which your wrapper should be doing
Almost everything is gonna be trying to stop you from being ratelimited
!d discord.TextChannel.slowmode_delay
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.
Only verified bots have more chances to get their limit raised cz uk why
yep
czechia and united kingdom?
I also asked for the same not to mention I deleted that bot cz, uhhh, we don't talk about it
"because you know why"
I can't spoonfeed that to you, but discord.TextChannel would be replaced by the name of the channel variable
or the channel object fetched directly
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Use the slowmode_delay property on the returned TextChannel object
@maiden fable why did menudocs and disnake tag up
define "it itsn't working"
errors? how's it behave now?
Okay nevermind I see a few issues here
achannel = bot.get_channel()missing argumentsachannel = bot.get_channel(channel)takes an ID, not a stringoldsm = achannel.slowmode_delay()slowmode_delayis a property ,not a function, so no need for()await ctx.channel.edit(slowmode_delay=(str(newsm)))slowmode_delaytakes an integer, not a string
awesome, let me know if there are any other issues
