#discord-bots
1 messages · Page 1140 of 1
youre sending an empty embed
oh
this is diff from neko
and you should use aiohttp if youre going to use the raw api

Well ig I’ll be back in 10 minutes 
take ur time
I’m back
i was bored so i made an ansi builder which i dont even know will work or not
only thing i would do is annotate the enum class vars with typing.ClassVar
whats the event called for whne you wanna clear messages
pretty cool
for example the !clear command
whats that event
oh yeah i'll be doing that
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
Pretty sure the limit kwarg would cover that
works finish, except for my choice of colors
now i need to add bold & underline
Wtf is an ansi 
one more question
read this
how do I check if a user has a certain permission
like manage messages
No documentation found for the requested symbol.
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
i forgot the s
what
whihc one is correct?
theyre both correct
Tjhe top of bottom one
it depends on your impl
ok
well basically im try8ng to make it so that if you have the manage messages permission u can clear messages
await ctx.channel.purge(limit=amount, check =)
how would I do it here
Like what would I put in check =
in the top of the command just do
@commands.has_permissions("manage_permissions")
even above the @bot.command?
under it
Okay
doesnt matter actually
and lets say
I wanted to do more than one
permission
would I just do "" and ""
how do i a, b, c = function()
with an async function?
add a , and next permissions
you would need to await the coro to get the result
a, b, c = await coro()
right now you only have the coro obj
Woah it gives me an error
coro # function obj
coro() # coroutine obj
await coro() # Any return type
@bot.command()
@commands_has_permissions("manage_permissions")
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)```
youre probably missing perms
says that commands_has_permissions is unreferenced
ah
remove the underscore after commands and put a period
which one
@commands**_**has_permissions
Should be @commands.has_permissions().
How can I make a toggle for a command? like ?automod true would make automod enabled and ?automod false would make it disabled
ah thx
oh ok something like this?
async def something():
# something
return chicken, cow, pig
@bot.slash_command()
async def my_command()ctx:
a, b, c = await something()
await ctx.respond(f"Animal 1 {a}, Animal 2 {b}, Animal 3 {c}")
Also how can I make it say that you dont have permission to do this command if the user doesnt have that permission
@bot.command()
@commands.has_permissions("manage_permissions")
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
Do I do if user.has_permissions != "manage_permissions"
yes except the ctx should be inside the brackets
type hint the toggle argument as bool, and then use a bot var or a class attribute (if you're in a cog) to keep track of the status
not in a cog
help pls
then a use bot var
!d discord.ext.commands.Command.enabled
A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the on_command_error() event. Defaults to True.
Change this to false on the command. Then it’ll be counted as disabled.
!d discord.ext.commands.Command.error use an error handler
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
How can I make it say that you dont have permission to do this command if the user doesnt have that permission
and to enable it?
Just do the opposite, changing it to True instead of False.
that'll disable the whole command, not the feature
Isn’t that what the message asked for?
No
what discord library are y'all using for bots these days? discord.py still?
yes
Ah it’s an auto mod command. Yea use what Lee said then
I didn’t look at the name of the command, just thinking of in general commands, oops
:p
What would be the function decorator? an event or command
what is type hinting? I always forget
dpy uses a converter for annotations
They're working on discord.py right now and were given until next year to catch up. I'm pretty optimistic they'd be able to do it before the deadline.
hikari. atleast for me
I heard hikari isnt as good anymore
but i cant say so myself cuz i havent used it lol
you use an instance of commands.Command (your command), and use it's .error method as a decorator
@bot.command()
async def some_command(...):
...
@some_command.error
async def some_command_error(...):
...
heard from? someone who didn't even touch it?
So can I do @bot.error
or does it have to be foo
i've personally used hikari, dpy 1.7.3/2.0 and almost all popular forks and finally decided to use hikari
no, foo is just your callback
callback?
maybe that'll clear it up a bit
@vestal island_command.error
nicee so we can't use decos without codeblock here 😂
@slate swan can you explain this ?
it's the name of the command's callback
oh ok
and does it have to be under like the command
or can it be anywhere on the code
it should be in the same file (and class if you're using cogs) where you defined your callback, after you defined it
use a list or something to keep a track of what guilds to ignore
it'll just be one guild
is automod some set of events?
I was just using that as an example. let's just say automod was a print statement I guess
so if it's toggled true it will print, if it's toggled false it will send a message to the channel
@bot.command()
@commands.has_permissions("manage_permissions")
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
# Cmd Errors
@clear.error
async def clear_error(ctx):
await ctx.send(f'Sorry {user} you can\'t clear messages.')
Is this good?
Oh wait I get an error when I say {user}
youre missing the error argument in your local error handler and user would be undefined
hu
So how do I fix that tho
that's not as complex as youre making it ```py
automod = True
@command()
async def foo(ctx, value: bool):
automod = value
@listen()
async def bar(msg):
if automod:
# its turned on
print(msg)
else:
# its turned off
me>?
would the bar have to be a listen?
y9su
and if youre going to use it in many commands just use a deco
how do i fix that
now that was just a pseudocode for an idea. you need to implement the whole thing yourself
I tried user=member
in the args section and it dindt work
indeed, the ✨ magic ✨ of decorators
i love decos like i love you
@bot.command()
@commands.has_permissions("manage_permissions")
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
# Cmd Errors
@clear.error
async def clear_error(ctx, user=member):
await ctx.send(f'Sorry {user} you can\'t clear messages.')
allot
still get errros F
You have to get the user attribute from some object.
hello so im wondering if theres anyway to make these look fancier? they all work though just want them too look better
Nvm.
😩 ily just like raven
you mean the code format?
- change client to bot
- run a black session
- remove useless spaces
So wait
dont forget about blackfire
How do i fix the error
and get the user who called the fucntin
Have you tried getting the user attribute from the ctx object?
How would I do that? ctx.user?
Yes.
I'm not sure if it will work though.
But let's try anyway.
ctx.author
hmm
Oh yeah.
author is the person who called the function?
raven still better
Let's test it.
yes
I haven't done anything similar and I kinda wanna see.
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
i wouldnt disagree
Okay and also what about the error handler?
that's why you wanna typehint stuff
thanks
!pip black in case you're wondering what black is
i'll also suggest typehinting things
any way to make queue look better? in discord wise
not in the format
we don't provide help related to YTDL code so
alright.
@slate swan it says that @command.has_permissions() doesnt take any positional arguments when I put in "manage_permissions"
it shouldnt be a string
manage_permissions=True like this
Oh
Ok
i got confused with has_role lmao
also i dont think manage_permissions is a permission, i may be wrong
uhh this is my code
asyncio.get_event_loop().run_until_complete(compress_video(f'{file_name}', f'{scrubed}.mp4', 8 * 1000))
this is the error i get while using it
WARNING:disnake.gateway:Shard ID None heartbeat blocked for more than 130 seconds.```
the @listen is supposed to represent what?
sorry my brain got tangle with some other stuff, he wanted manage_messages
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
if it's a listen wouldn't it not be invokable?
its a deco to register event listeners internally
:/ i wish this would work lmao
I am getting another error for this code it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: clear_error() takes 1 positional argument but 2 were given.
This occurs whenever someone without the manage messages permission says .clear
Heres the code:
@bot.command()
@commands.has_permissions(manage_permissions=True)
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
# Cmd Errors
@clear.error
async def clear_error(ctx):
await ctx.send(f'Sorry {ctx.author} you can\'t clear messages.')```
that probably happen because your client got blocked from sending hbs or receiving them
Whenever someone says .clear 5 without the permission
it gives that error
and it says 1 pos only but 2 were gfiven
hmm is there way to allow it to send hbs while working on an async task that the commands code needs to wait until its done
you forgot the error argument
ctx, error?
yup
and that makes sure what happens
tOhh
the error that was raised
If I want my bot to be installed on many servers, whats the best way to handle the settings of each server separately? Use a backend table? anyone seen any guides?
probably a db with all the configs
automodtoggle = True
@client.command()
async def automod_toggle(ctx, value: bool):
automodtoggle = value
print(automodtoggle)
@client.listen()
async def automodlisten(msg):
if automodtoggle:
automodtoggle = True
else:
automodtoggle = False
@client.command()
async def automod(ctx):
# do something
if automodtoggle:
print("automod on")
else:
await ctx.send("automod on")
``` @slate swan could you help out? I know I did something wrong
youre making a new variable in a function local scope
as sarth showed you need to reassign the value of a global variable
so in this case automod
Which variable
still gives an error whenever someone types .clear without having the permission
and what should it be?
probably false if its not true
!d asyncio.to_thread For things like that, you’ll want to run it in some other thread, you may also use run_in_executor, but to_thread here will probably be your simplest fix. There is also an example in the documentation I suggest you take a look at that.
coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.
Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were ran in the main thread. For example:
What’s the difference?
iirc run_in_executor makes a thread pool
I checked the documentation and everything to find the error but I am not sure what is the exception and what should the type be?
wait so how do I fix it? I think I confused myself even more
did you save file/restart your bot after you made your changes?
yes
I restarted it too
this is a cool diagram
is there anything wrong with my code
Matter of fact, to_thread just calls run_in_executor
@slate swan ?
python will never support slash commands?
what
python doesnt support slash commands
discord.py does🤞
I coulda swore
yeah that's what I meant
pleaseee someone help
So I've been lied to
has anyone connected discord.py to a db for storing settings per server?
2.0 does lol
in a new thread, while in run_in_executor you have control over what loop to use
alr ty
I thought they brought it back?
@slate swan can you explain in simpler terms what I did wrong?
question how would you even run 2 event loops without an exception and wasnt it bad?
*executor to use
Valid point
ah 😅
you need to update the automod variable, not the variables you define in those functions
could you send the full traceback?
nvm got it to work
to_thread is basically
run_in_executor(None, coro)
another reason why i asked to use run_in_executor is because the loop is directly accessiable using bot.loop, so you dont need to import asyncio
so change automodtoggle to automod?
yep
@slate swan like that?
like.. what?
.
yeah try it and see
can someone help me on a welcome command that will look like this? i have the code. theres no errors it just wont send
Both true and false are only printing
https://pastebin.com/E8R6b4YN
i wanted to know how to do this generally and tried to implement it in my bot but i dont think its doing anything?
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.
i believe im doing it correct rarity, name, patk, matk, defense, agt, element, classs, perc = await gacha()
How do I make it so that it also sends something in the actual discord channel when a user leaves
await ctx.send(f'{member} has left the server.')
with what Context?
he has to add it
the event doesnt take any context
he should just use channel.send though
no it wont take context
i tried that already
define the channel id and just use channel.send?
Ok
and lets say that this bot was used in more than one server
and if we wanted to get that ID
of the general channel
is that possible?
that's more complicated @slate swan probably can help you there
@slate swan
well first how do I make it send a message when a user leaves
how do I do the slash commands?
channel = bot.get_channel(channelid)
await channel.send(f"{member} has left the server.)
Ahh
thx
no problem, test it out first
so idk where to ask it, so i ask here (because it's part of my bot). I have a html file which copies and need to get replaced Username with actual username and avatar with avatar.png, but when i use data.replace it does not replace anything, so i get unworking html.
with open("./templates/example.html") as f:
data = f.read()
data.replace("username", f"{ctx.message.author.name}")
data.replace("avatar", "avatar.png")
print(data)```
can someone help me on a welcome command that will look like this? i have the code. theres no errors it just wont send
What's the code?
i can show/send it if yu want
well, just send here, i'll watch.
just upload the leave message part
!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.
oh didnt send full code
await ctx.send(file=discord.File('rank.png'))```
here's an example of how to add it to message
is there a way to get rid of all the errors at the end such a runtimerror when the loop is closed and instead just say the bot is offline.
Whenever I stop running the script
it gives so many errors
oh, wait, i'm dumb, i telled you about leave.
haha
ah jeez. this hurts me
well, just try to turn it on.
wym?
ive ran it before and when i have someone join it does nothing
no errors just plane nothing
nothing in terminal is what i mean
i'm about intents
it is off by default, you need to turn it on on website and then in code
well i did try to upload it to stackoverflow and had this
Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.
Did you tried turning on intents? It's not that hard that you need a stackoverflow. Just go to developers, bot and you will see it. Then find in internet code to put them on in code and that's it
yes
well, then idk. For me intents too don't work, so in economy i just put everywhere a checks in database.
# Kick
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member} was kicked because {reason}.')
embed = discord.Embed(title='KICKED', description=f'Reason: {reason}')
await member.send(embed=embed)
print(f'{member} was kicked because: {reason}')
# Ban
@bot.command()
@commands.has_permissions(kick_members=True, ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'{member} was banned because {reason}.')
embed = discord.Embed(title='BANNED', description=f'Reason: {reason}')
await member.send(embed=embed)
print(f'{member} was banned because: {reason}')
Is this code valid? Does anyone see any errors
@slate swan
you have to send the embed to the user first before banning/kicking them iirc
pretty much, yeah
anyone know how i can make this look better? (dsicord-wise)
I keep getting errors
For the unban command
Does anyone know the issue?
btw i did Lukas tutorial idk any other way
im trying to use giphy for something but i get this
anyone know why?
i have giphy_client installed in terminal
when i use my help command, it sends it 2 times :/ idk how to fix it because i dont believe there is anything i did
how to do this but with JUST HEADERS
url = "https://discord.com/api/webhooks/[redacted]/[redacted]"
headers = {
"content-type": "application/json"
}
data = {
"username": "Webhook",
"content": "Hello, World!",
"embeds": [{
"title": "Hello, Embed!",
"description": "This is an embedded message."
}]
}
res = requests.post(url, headers=headers, json=data)
Why not use the lib itself....?
he cant answer the question🗿
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
It takes a username kwarg too
Can someone help me
Ive been trying to make an unban command for the last hour
and I dont know what to do
all the YT tutorials are expired
@slate swan
@client.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
You can do same with user.id
anyone able to help me fix a welcome command? its kinda complicated i think it may have some indent problems but i cant seem to figure it out
Sure
so it doesnt get any errors nothing in terminal it just when someone joins it doesnt do anything
No please don't just no
@bot.commans()
async def unban(ctx, id: int):
await ctx.guild.unban(discord.Object(id))
It's just my guess, but your get_channel might be returning None
man 😔
Don't ever follow Lucas
I don't
That unban command is from Lucas
I saw from a website
Then don't follow the website (:
noted 🗒️
how would i fix?
i changed it a little
and didnt think it would do anything and it didnt
Are you putting a channel ID in get_channel() ?
[download] 100% of 2.82MiB in 01:00
INFO:disnake.gateway:Timed out receiving packet. Attempting a reconnect.
INFO:disnake.client:Got a request to RESUME the websocket.
INFO:disnake.gateway:Shard ID None has sent the RESUME payload.
INFO:disnake.gateway:Shard ID None has successfully RESUMED session 673cf17d6b9ec83faf24f1d01a6adadb under trace ["gateway-prd-main-5mnx",{"micros":831,"calls":["discord-sessions-green-prd-2-155",{"micros":39}]}].
Ignoring exception in command download:
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\wbencode.py", line 105, in download
await ctx.send(file=disnake.File(filename))
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\abc.py", line 1512, in send
data = await state.http.send_files(
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\http.py", line 365, in request
async with self.__session.request(method, url, **kwargs) as response:
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
self._resp = await self._coro
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 559, in _request
await resp.start(conn)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client_reqrep.py", line 898, in start
message, payload = await protocol.read() # type: ignore[union-attr]
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\streams.py", line 616, in read
await self._waiter
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
yes
use !paste
That takes a server Id i guess
!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.
idk maybe i might just have to re do the whole thing i really want it to be liek this https://cdn.discordapp.com/attachments/343944376055103488/994748576209051658/unknown.png
but ill find another way probably
Try putting the server Id, and the variable will have a list of channels. That's my guess
heres my error while trying to download the file to encode and it gets the heartbeat errors
https://paste.pythondiscord.com/kawunoriku
well idk its suppose to just send in one channel which is just called welcome
Uhhh
@slate swan try running this
channel = client.get_channel(<id>)
@client.event
async def on_ready():
await channel.send('ready')
You need to get the channel within the event
this will never work because the channel won't be cached before bot.run()
yeah
def*
there
and where will it take the channel?
to the welcome channel from channel id
also putting that kind of stuff in on_ready function is not a very good practice as i heard
yes
wasnt me
it might just doesnt work
just a print is enough
just put in what he said
well im trying to figure out why it wont send errors or d oanything i have channel id already in but it just wont do anything
channel = client.get_channel(id) or await client.fetch_channel(id)
alr i did that then put the id in and run and when it joins i get this
no errors in terminal
thats why i think i would have to re do the whole thing
https://cdn.discordapp.com/attachments/343944376055103488/994748576209051658/unknown.png trying to make it look like this but when they join it will show pfp name etc
client.send()?
Is there a way to make a command to add other commands?
idk i deleted it im gonna re make it some other time
you should fetch the channel on first line, and do channel.send on the second
what would be a way
do you want to make a new command with an existing callback? do you want to make a new command with a "on-the-fly" callback? do you want to add an existing command to another command as a subcommand?
the way i did it - i made a command class, which has some information about it and it has execute method, and i put those in a dictionary
but that makes sense tho
not sure what you mean. basically I'll be able to do !addcommand <newcmdname> <cmdtext>
then when I do !newcmdname it will send the <cmdtext>
there is probably a better way to do it
i use jishaku and add commands in an eval using bot.add_command.
you'll have to use eval/exec then (or jishaku)
What's that
any eval tool/command which allows you to access your bot var can help you do that
!pip jishaku
A discord.py extension including useful tools for bot development and debugging.
standart python function
evaluates or executes python code
>>> result = eval("2 + 2")
>>> print(result)
4
>>> result = exec("print(2 + 2)") # 'result' would be None
4
seems like it makes it quite easy
I have no clue how to use it
start by installing it pip install -U jishaku
then?
now depending on what version of dpy you're using you would have to load it as an extension using ```py
bot.load_extension("jishaku")
#or
await bot.load_extension("jishaku")
can I not just use a json dictionary? with the command name as a key
sure ofcourse you can
that'd be heaps simpler, no?
but don't expect that it would be much scalable
and it will be more complicated i guess
What do you mean?
like how would the bot know that the dictionary key is a command, the only choice you have is using on_message with that
how would that be more complicated
what do you not understand
with that extension seems like you can easily manage that stuff with a few lines of code
nothing
I have no clue how lmao
while with json or anything like that you have to implement your own system
expect means to wish for
scalable means being able to handle large amount of data
there is a documentation i think
you don't really need to go into much of document. its just a basic eval
prefixjsk py ```py
@commands.command()
async def command_name(ctx):
await ctx.send("your message")
_bot.add_command(command_name)
With the command name being?
with the command name being the command name you want mb
would it be possible to specify the command name within the !addcommand <cmdname>
that would require you to setup a storage which saves the responses of your commands, and a custom parser which checks for the commands added by your !addcommand command in on_message events.
because discord.py's commands extension won't do that for you
do note that all of the commands that you add will no longer exist once you restart your bot
as you have been told exec and eval are also usable but that's too unsafe
this too^
i think just a json dictionary will be way easier
yup, until he saves those somewhere else
imagine someone doin !addcommand (await bot.close()) and you exec it
just create a tag system like R Danny and many other bots have
much easier and Efficient than the addcommand thing
what's your goal with creating a command on the go?
btw, it might be not a very proper channel, but, how to make text to be a paragraph etc inside those hints?
what hints?
you mean the int and str?
mhm
the format looks fine to me, your doc parser will format it the way it should be automatically
I'll assume you're using sphinx?
those that are created right at the start of function of class using
"""
...
"""
oh, doc strings
Well, in order for it to be a paragraph, you'd need to actually write a paragraph?
Your docstrings as of now are just sentences
"""
About class
Attributes
-----------
attr: :class:`type`
"""
``` is how you make the docstrings generally
i see, welp thanks
If your using sphinx you'll need to install the napoleon extension, cause this is a spin-off, hybrid of the google docstyle
not really, i've been using this in sphinx with just autodoc
Well, for sphinx 1.3+
im making a afk command it works but when ever i do reason going to eat it will not work with spaces? how do i get it to work with spaces
- arg
use it like !afk "this is a reason with spaces" time or change the format to ```py
async def foo(ctx, minutes,*, reasons):
...
ah
@slate swan how can I add new information to the json dict?
just update it like a normal dictionary and use json.dump to save the updates
def get_config(name):
file = Path(f"{name}.json")
if not file.exists():
file.write_text("{}")
return json.loads(file.read_text())
@client.command()
async def addcmd(ctx, name, *, text):
newcmds = get_config("newcmds")
got this so far
like this?
wait just seen theres a error
remove the s
since dpy uses type annotation converters, type hint int to minutes, otherwise it'll return a string instead of an integer
can I see an example of dumps?
yeah
the mention doesnt work
imma try to see if i can spaces now
- if the bot goes offline and a new session starts, it wont care about the old one
- editing member without permission check, if your bot doesnt have permissions to edit the nickname of the the member, this command totally fails ( what if the owner used to command???)
3:pass_contextwas removed 3 + years ago
ah
so i shouldntbe using pass_context
it's not gonna hurt you in any way if you have it there, it just doesn't do anything anymore. So it's kinda pointless in having it
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
this is it now but now when i say a word (2 words) walking dog it only will say the 2nd part
because the first one is consumed by the mins
ah
well
you can't dump on a dictionary?
no
then that wouldn't work.?
youre dumping in a json file using that method, not a dictionary
the json file contains an empty dict
its not a dict its a javascript object fyi,
Oh but still?
did you read the doc i sent?
json.dump(your_dictionary, the_json_file_buffer)
``` is how it works
Yeah it said AttributeError: 'dict' object has no attribute 'append'
show code
@client.command()
async def addcmd(ctx, name, *, text):
newcmds = get_config("newcmds")
newcmds.append(f'"{name}": "{text}"')
!e ```py
new_cmds = {}
name="name"
text="text"
try:
new_cmds.append(f'"{name}": "{text}"')
except:
print("dont do this.")
new_cmds[name] = text # do this
print(new_cmds)```
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | dont do this.
002 | {'name': 'text'}
Why ?
yk what try/except is right?
yes
so that just says that you're doing it wrong and dont do that
append is a method of list, not dictionaries.
you would be using dict[key] = value for adding data to a dictionary.
does it automattically add the quotation marks?
wait what quotation mark?
if its already a string , it is.
you dont need to mess with it
like
{"key": "value"}
see this example
@client.command()
async def addcmd(ctx, name, *, text):
newcmds = get_config("newcmds")
newcmds[name] = text
like this?
hm yeah
hey does any1 know a good guide on how to collect info when somebody joins a discord server
for example im tryna store: join date, username, profile pic (if possible), Discord ID
I figured it out thanks, how would I remove a cartain key:value by the key name?
!d discord.on_member_join there's a Member object containing all the data you need, check docs about that class
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
great ty
!d dict.pop
pop(key[, default])```
If *key* is in the dictionary, remove it and return its value, else return *default*. If *default* is not given and *key* is not in the dictionary, a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError") is raised.
@client.command()
async def removecmd(ctx, name: str):
cmds = get_config("newcmds")
del cmds[name]
with open('newcmds.json', 'w') as f:
json.dump(cmds, f)
this should work too ?
@vale wing
yeah it will work
tbh i prefer pop over del cause ez
@client.slash_command(name = "ban", description = "Bans a member")
@commands.has_permissions(ban_members = True, administrator = True)
async def ban(ctx, member: Option(discord.Member, description = "Who do you want to ban?"), reason: Options(str, description = "Why?", required = False)):
if member.id == ctx.author.id: #checks to see if they're the same
await ctx.respond("BRUH! You can't ban yourself!")
elif member.guild_permissions.administrator:
await ctx.respond("Stop trying to ban an admin! :rolling_eyes:")
else:
if reason == None:
reason = f"None provided by {ctx.author}"
await member.ban(reason = reason)
await ctx.respond(f"<@{ctx.author.id}>, <@{member.id}> has been banned successfully from this server!\n\nReason: {reason}")```
I get Option is not defined
from discord import Option
or use discord.Option
@client.add_command(name = "ban", description = "Bans a member")
@commands.has_permissions(ban_members = True, administrator = True)
async def ban(ctx, member: Option(discord.Member, description = "Who do you want to ban?"), reason: Option(str, description = "Why?", required = False)):
if member.id == ctx.author.id: #checks to see if they're the same
await ctx.respond("BRUH! You can't ban yourself!")
elif member.guild_permissions.administrator:
await ctx.respond("Stop trying to ban an admin! :rolling_eyes:")
else:
if reason == None:
reason = f"None provided by {ctx.author}"
await member.ban(reason = reason)
await ctx.respond(f"<@{ctx.author.id}>, <@{member.id}> has been banned successfully from this server!\n\nReason: {reason}")
@client.add_command(name = "kick", description = "Kicks a member")
@commands.has_permissions(kick_members = True, administrator = True)
async def kick(ctx, member: Option(discord.Member, description = "Who do you want to kick?"), reason: Option(str, description = "Why?", required = False)):
if member.id == ctx.author.id: #checks to see if they're the same
await ctx.respond("BRUH! You can't kick yourself!")
elif member.guild_permissions.administrator:
await ctx.respond("Stop trying to kick an admin! :rolling_eyes:")
else:
if reason == None:
reason = f"None provided by {ctx.author}"
await member.kick(reason = reason)
await ctx.respond(f"<@{ctx.author.id}>, <@{member.id}> has been kicked from this server!\n\nReason: {reason}")```
I get this error:as c:\Users\Clicks\Desktop\Timmy (smile)\bot.py:8: DeprecationWarning: The asyncore module is deprecated and will be removed in Python 3.12. The recommended replacement is asyncio from asyncore import loop Traceback (most recent call last): File "c:\Users\Clicks\Desktop\Timmy (smile)\bot.py", line 379, in <module> @client.add_command(name = "ban", description = "Bans a member") TypeError: BotBase.add_command() got an unexpected keyword argument 'name' Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x00000188FDEFB580>
its Bot.command Bot.add_command is another method
c:\Users\Clicks\Desktop\Timmy (smile)\bot.py:8: DeprecationWarning: The asyncore module is deprecated and will be removed in Python 3.12. The recommended replacement is asyncio
from asyncore import loop
Traceback (most recent call last):
File "c:\Users\Clicks\Desktop\Timmy (smile)\bot.py", line 380, in <module>
async def ban(ctx, member: discord.Option(discord.Member, description = "Who do you want to ban?"), reason: discord.Option(str, description = "Why?", required = False)):
AttributeError: module 'discord' has no attribute 'Option'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000020B26BFFA30>
discord.Option is not a thing, what are you trying to do?
those aren't even slash commands overall....
what library are you using again?
cause i don't think its discord.py by the command structure
What is this error?
what are the different ways one can set up cogs, instead of doing this in each file ```py
def setup(bot):
bot.add_cog(Cog(bot))
i thought discord.Message.author returned the discord.Member object?
you can call add_cog() while initiating your bot (for example setup_hook), but you need to import the cog's class
it returns should return Member but it may return User if the member has left the guild
hm, i share the same guild as this bot yet i am getting User when i trying to iterate through my roles.
could it be because i am DMing the bot?
@client.command() async def kick(ctx, member : discord.Member): if ctx.member.voice is not None: await member.move_to(None) print("Kicked user.")
And?
Remove ctx.
anyone know why im getting Attribute Error: 'Context' object has no attribute 'member'
if member.voice is not None
ctx.guild.roles.count
``` this is correct?
ok
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'builtin_function_or_method' has no len()
What code did you use?
What line of code did you put in?
You changed this to what?
len(ctx.guild.roles.count)
Remove the .count at the end
no because there isn't any > operand, i just want to convert a str into an int
just cast int to the variable inside a try except block
, casting of int to a non-integer value raises ValueError
nothing in the console, you don't help me you make the thing more difficult
exec("try: val=int(val)\nexcept ValueError: print('no')")
ew
its pythonic
string = "1 2 3 4 5 $"
val = int(''.join(char for char in string if char.isalnum() and char.upper()==char.lower()))
nice

s1 = await client.wait_for('message')
s1 = s1.content
s1=int(s1)
ValueError: invalid literal for int() with base 10: ''
help me pls
Lol read the message above we have discussed that 'til now
The content is an empty string, either the message has no content or your message_content intents are missing
cant you just use str.isdigit() ?
👁️ 👁️
Ashley shared a weird way to do that so i shared a way even more weird 
both of you, to the esoteric corner 😡 👉 #esoteric-python
oh no 
this hurts me more than it hurts you😡
does anyone understand how to make embeds? I'm really confused but i want to make this information into an embed instead of a boring message:
bot_message = f"{message.content} - {message.author.name} - {datetime.today().strftime('%d/%m/%Y')}"
here is the rest of my code
`import discord
from datetime import datetime
client = discord.Client()
@client.event
async def on_ready():
print("Ready")
print(f'Logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
channel = discord.utils.get(message.guild.channels, name="quotes")
bot_message = f"{message.content} - {message.author.name} - {datetime.today().strftime('%d/%m/%Y')}"
await channel.send(bot_message)
print(f"{bot_message}")
client.run('bot token')`
!d discord.Embed
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.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
ty
int(''.join(__import__('re').findall('\d+', text)))
using regex smh
let's make a library that converts a string to a number for you 😭
ok
quickest algorithm to convert str to int implemented in c, sounds good 😄
who cares about speed, we use assembly no matter what
mcqueen
thats my name, yes
I removed the commit
create the table lol
I created
open the sql terminal, and check if the table exists
import aiosqlite
import discord
from discord.ext import commands
import asyncio
async def get_prefix(Bot, message):
connect = await aiosqlite.connect('prefixes.db')
cursor = await connect.cursor()
id = message.guild.id
await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
prefix = await cursor.fetchone()
try:
print(prefix)
return prefix
finally:
await connect.close()
bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())
async def connect():
bot.connect = await aiosqlite.connect('prefixes.db')
cursor = await bot.connect.cursor()
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
await bot.connect.commit()
await bot.connect.close()
bot.setup_hook = connect
@bot.event
async def on_ready():
print("ready")
@bot.command()
async def test(ctx):
await ctx.send("working")
@bot.command()
async def set_prefix(ctx,newpre):
id = ctx.guild.id
connect = await aiosqlite.connect('prefixes.db')
cursor = await connect.cursor()
await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
await connect.commit()
await cursor.execute('UPDATE prefixtab SET prefix=? WHERE guild_id=?',(newpre,id))
await connect.commit()
await connect.close()
See the connect function
hmm hold on
why are you committing after a SELECT 🤔
Hi guys, i'm new here 🙂 a question about Discord bots: is there anything available - and functional - that can pull Moodle's notification and events and bring to Discord?
maybe some way to create a Webhook or something like that
if that helps
next level sqlite logic 😔
Sounds like something you'd do tbh
Good morning okimii
i have no clue why the table is not created, sry
how many times do you wake up a day?
imagine humiliating me for no reason 😔
Good morning Zeffo
you sleep?
dem
yes regularly 😎
red head moment
😔 teach
code in c
{str(len({m.id for m in bot.get_all_user() if m.status is not nextcord.Status.offline}))} this is correct?
thanks! do you know if i need to be the administrator of a Moodle course to setup that? or being a student from this course is possible?
sorry if it is a dumb question, but i am not familiar with that
idk
run and see if you get the desired output
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 445, in _run_event
await coro(*args, **kwargs)
File "main.py", line 534, in on_command_error
raise error # or if u dont wanna get errors in ur command prompt, use pass
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 1117, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: 'Bot' object has no attribute 'get_all_user'
what is get_all_user?
online users
+-+
What should I do now?
well, bot doesn't have that method
there's bot.users and bot.get_all_members
create table separately?
directly via sqlite terminal or something
sad
😢
why are you on mobile 😭
why not bro
Is there any prob
YES
Not to me
does anyone know why this is happening?
its not meant to be coded on... and most of the fixes we give, will not apply to you as you can already see
here is my code
you're probably passing the Embed to content instead of the embed kwarg
What should I do to create table on replit?
then ask there....
reset your token bro
RESTToken
dw i already did
good
thats like from ages ago
how do i fix that i am very new to the discord api and python and i am rlly confused
embed=embed
!tags positional-keyword
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• !tags param-arg (Parameters vs. Arguments)
embed kwarg...
what is kwarg
the kwarg is embed so you would do embed=quote
They told me to provide more information to create table
await channel.send(embed=quote)
ok ...
how to remove old commits from pycharm vcs
whats a vcs
ah
now the prev commit was like a 1gb file which i commited by mistake and now it's not letting me push
;-;
Can I ask about one thing
How can i check that a cell is empty?
empty as in Null?
Ye
in SQL or python
Sqlite3 python
This
cursor = await self.db.cursor()
await cursor.execute('SELECT * FROM tempban')
data = await cursor.fetchall()
now = int(time.time())
if data == []:
return
for data_tuples in data:
guild_id = data_tuples[0]
guild = await self.fetch_guild(guild_id)
user_id = data_tuples[1]
user = await self.fetch_user(user_id)
till = data_tuples[2]
if till >= now:
try:
await guild.unban(user=user, reason='Auto unban after {} days'.format(int(till/86400)))
except:
pass
await cursor.execute('DELETE FROM tempban WHERE guild = ? AND user = ?', (guild.id, user.id,))
I made this loop to unban tempbanned user, when the timestamp is for 7 days why does it unban in 1 day-
nvm i got it pushed now
what?
🥳
you want to get non empty values?
So I'm trying to make a 'set and forget' faq menu. The goal is I get the bot to send a message with a view and then that message and view never needs to be resent (unless it gets deleted/outdated). Ik I need to set a timeout=None and custom id="a_name to have a persistent between restarts view but should I also be setting a messsge_id when it adds the view with self.add_view(view, message_id=... during the setup hook to get the type of persistence I mentioned above? (d.py 2.0)
you don't really need the message id
Do you mean that generally or for my use case? When would be a good idea to use it?
your case
Okay thanks
is there any way to find the time in locale of a user?
For ex guild id of message 5738883
I want to check if the prefix value of 573883 is empty or not
@paper sluice
!pip pywin32
!pip keyboard
import aiosqlite
import discord
from discord.ext import commands
import asyncio
async def get_prefix(Bot, message):
connect = await aiosqlite.connect('prefixes.db')
cursor = await connect.cursor()
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
await connect.commit()
id = message.guild.id
await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
prefix = await cursor.fetchone()
try:
print(prefix)
return prefix or '@'
finally:
await connect.close()
bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())
async def connect():
bot.connect = await aiosqlite.connect('prefixes.db')
cursor = await bot.connect.cursor()
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
await bot.connect.commit()
await bot.connect.close()
bot.setup_hook = connect
@bot.event
async def on_ready():
print("ready")
@bot.command()
async def test(ctx):
await ctx.send("working")
@bot.command()
async def set_prefix(ctx,newpre:str):
id = ctx.guild.id
connect = await aiosqlite.connect('prefixes.db')
cursor = await connect.cursor()
await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
print("selected")
await connect.commit()
await cursor.execute('UPDATE prefixtab SET prefix=? WHERE guild_id=?',(newpre,id))
print("updated")
await connect.commit()
await connect.close()
await ctx.send(f"updating prefix to {newpre}")
My get prefix is returning me null but i have updated the value
How can I make this code more better?
I'm out, I'll point out a nice amount of mistakes and I'll get sued
mhm
Hmmm
Examples (I think) are there
excuse me? that's what they are using?
Idk what's context manager
Do you found mistakes?
first of all, they shouldn't be connecting to the db on each command. And by the context manager I meant this```py
async with bot.db.execute(
"SELECT column FROM table WHERE query = ?", (query,)
) as cursor:
result = await cursor.fetchone()
Instead of ```py
cursor = await connect.cursor()
await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
print("selected")
await connect.commit()
and why are you committing a select operation?
- Don't connect to the database every time a message is sent. In essence, don't connect to the database in the
get_prefixfunction every time, rather use a global connection. - Don't make unnecessary SQL queries (creating the table in get_prefix)
- Don't name variables with reserved keywords (
idin get_prefix) - Don't use
tryandfinally, instead use a conditional or a simpleorstatement ->return prefix or '@' - Don't close the connection in the
connectfunction, rather use the same connection everywhere (in get_prefix too)
there are more errors in the set_prefix command
Can I ask one thing?
Don't connect to the database on each command invocation, You don't need to SELECT to update
?
Like i write the get_prefix func on top of bot varibale and did connect at down
My code would not work
So how to make it work?
subclass the bot class easy
get_prefix is not even a class how would you subclass that 
Bruh
"bot class" -> commands.Bot
use brain
😫
not necessary
!e
class Foo:
def _alias(self):
self.not_alias()
def not_alias(self):
print("Ashley is so uwu")
Foo()._alias()
@slate swan :white_check_mark: Your eval job has completed with return code 0.
Ashley is so uwu
I make voice state but..
There is a problem:
if you are in a voice channel and execute the command, the current time is displayed.
I haven't found a solution yet.
Whats the best way to make a timed mute command?
Is asyncio.sleep() alright for 30 days?
just consider discord timeouts
yeah thats what I was thinking, is it worth doing it via a database
why do you need a database?
How else would I store the mute information for a member?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
a db isn't necessary if you're using timeouts
You want to log the mute information, right?
Right but im wanting it more of a role, not timeout
but why?
Because its channel specific
oh hmm
it would be nice if you could do something
what behaviour are you expecting?
all that hassle of creating a db and stuff gone now 😔
so you want to log the mute information? For like a command that shows all the member's mutes?
All active mutes, how long each mute has left, etc.
While I am on a voice channel and I am using a command it shows me the current time instead of the time I was in total on the voice channel.
Will you help me?
to be fair I can worry about that down the road, just want a reliable role persist / temp mute by role
and feel asyncio.sleep() could cause issues if the bot were to go offline
so use a timeconverter to convert a duration to seconds
yeah it will
and use a db to track the active mutes. Within a task loop, use time logic to know whether a member's time expiry is up and unmute them.
you will have to have a db to store the mutes and an async task to unmute the mutes which have expired
how long have you been in the voice channel for, before using the command?
how often you think for the task loop
A few seconds,
It was supposed to show me the number of seconds I'm in voice channel and not the current time in seconds
when the bot starts (only once), the task will handle the mutes which shouldve been unmuted when the bot was offline
use asyncio.sleep to unmute when the bot is online
use logic of, for example, if mute_time >= time_now
thats true and would be easier but would allow for less information on the mutes
so yeah db with timedeltas and loop to check those could be better?
yes, don't use asyncio.sleep
how long should I loop for each check?
Why do I get runtimeerrors whenever i end the script? How do I prevent this from happening
what do you mean?
you mean how often to loop?
yes
thats not what i mean, when the bot starts run a task to unmute users (only once) and in the mute command add the data to the db and use asyncio.sleep to unmute the user when the bot shutdowns the asyncio.sleep wont work thus the task will do the unmuting when the bot is online again
Who can help me? please
why use both? I would suggest one
the task is only ran once
and this method prevents some issues when using tasks.loop
15 seconds should be okay? if doesn't really matter
what are the issues with tasks.loop?
yeah I know what you mean im just saying that to get precise information on time left of each mute, and see current mutes, it would be easier to check the deltas if the mutes are stored in a database
the method i mention uses a database 
yeah, when the mute command is done, why input all the other information except the mute duration and use asyncio.sleep for the unmutes

I see
So I still store mutes in a database to check its information, but as far as unmutes go, just use sleep. And have a task on startup that checks deltas of current mutes and see if they need to be unmuted?
yeah
Hi, I got a little problem.
My bot is working so far, but it doesn't load the cogs for some reason.
import discord
import os
from discord.ext import commands
owners = [456458873453150208, 688293803613880334]
class LateNightModeration(commands.Bot):
def __init__(self):
super().__init__(".", case_insensitive=True, intents=discord.Intents.all(), strip_after_prefix=True, owner_ids=owners)
async def setup_hook(self):
```Until here everything is working so far.
```py
self.remove_command("help")
```The standard help command doesn't get removed for some reason, so I guess that "setup_hook" isn't being called for some reason
```py
for extension in os.listdir("./cogs"):
if extension.endswith(".py"):
await self.load_extension(extension)
``` Also the cogs aren't getting loaded
```py
async def close(self):
await super().close()
async def on_ready(self):
print("main.py has been loaded.")
```This gets printed
```py
bot = LateNightModeration()
@bot.command()
async def test(ctx):
await ctx.reply("hi")
```The command is also working. I'm running the bot with "bot.run("")", so I'm really not sure where the mistake could be.
setup hook gets called only when you .start() the bot within an context manager
async def main():
async with LateNightModeration() as bot:
await bot.start()
asyncio.run(main())
``` replacing bot.run() with this will trigger the on_ready
import aiosqlite
import discord
from discord.ext import commands
import asyncio
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix="@",help_command=None,intents=discord.Intents.all())
bot = botclass()
So i subclassed
So where would be setup hook now?
it would be at the same indents as of def init
Ah damn, I just looked at the docs on how to migrate to d.py 2.0 and I thought that this won't fix my problem. Thank you, really appreciate it
guys where can I ask my questions about my code
Oof i not mean that
if its discord bot related just drop it here, else you can go to the topical channel related to your topic or claim a help channel #❓|how-to-get-help
pleasure, lemme know if you face some issue with it
elaborate then
Actually my code was trash
So Ashley told me to subclass bot
So i asking now where should I do setup hook code
as i said, in the botclass, with the same indentation as your init dunder
Ok
what do you not understand in it?
I understood
!pip pyautogui
?
async def setup_hook(self):
'" your uwu logic '''``` in the subclass
the docstrings are cursed enuf to ruin my day
!pip pymsgbox
?
staph
this is #discord-bots channel
not #bot-commands
Why using commands here?
🗿 okay mam
@slate swan will it be self.bot.connect = "connection here"
Or bot.connect = "bruh"
async def setup_hook(self):
async with aiosqlite.connect("prefixes.db") as self.connect:
Is it correct?
Yeah well, I actually did, here's the traceback no clue what this is telling me
what's your discord.py version? use pip show discord.py in the shell
I got 2.0 from the github, I cloned the repo
if you installed discord.py 2.0 in replit using pip, thats your issue
did you use pip?
Hm, it worked on another repl, it's strange that it doesn't work on this one. I used pip install -U git+https://github.com/Rapptz/discord.py
yeah it works, but only for one time.
poetry add git+https://github.com/Rapptz/discord.py``` use this cmd
This will take years
replit being replit, takes barely 13 seconds on a local device
I honestly should consider switching back to a VPS
you can either os.environ["TOKEN" or os.getenv('TOKEN')
Ah, it was os.environ just got confused for a second, my bad
you definitely should, there are many ways how replit is bad, check pins of #965291480992321536 for reasons
if you have a credit card or debit card you can easily get free micros from aws, orcale and google for 2-3 years combined
I had a pretty decent VPS before, but I stopped using it because someone told me that repl.it is actually good for discord Bot hosting and I believed them lol
the worst advice 💀
Block that person
Will do, thanks for the advice
the only thing i like about replit is the multiplayer and enforcing poetry 😻
nothing good for hosting purpose tho
Ever tried out the multiplayer in Pycharm? That's a really good one ngl
i agree, tho i use VSCODE live share
Never heard of that
Anddddd this convo would make more sense in #editors-ides thanks

You're welcome
Is maintaing a forked dpy library yourself hard, specifically adding the new discord features to the lib
Huh?
Your making it harder by not doing what I’m asking you
@maiden fable would you know?
Depends on yr skill level. If u have enough time and knowledge about APIs and ws, then it's not that hard
i fixed it, i just wanted to convert a str to a int if you can't help its not a problem just don't ping me
Yes and to debug that you needed to print
What's ws?
good afternoon
websocket
I could help if your did what I asked???
Websockets
please be more patient with the helpers
furthermore, this is not the appropriate channel to learn python basics
i'm patient, just he tell me something wrong + insult me + just wanted to know how to convert something, found by myself
nice
that's it and he continue to ping me even if i say its finished
!e
class uwu:
def __init__(self, value):
self.val = value
def __gt__(self, obj):
self.val > obj.val
one = uwu("1")
two = uwu(1)
print(one > two)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | File "<string>", line 5, in __gt__
004 | TypeError: '>' not supported between instances of 'str' and 'int'
no
thank you but i found the error in my code that's kind of you
why would it be ew
(no homo)
love you too
no that's just me
What did I just run into 🐒
us
lovely
👁️
Why is ash in such a good mood tf
wrong eyes
cyclopes?
I can hear the sarcasm behind every message
back to this
loooooooool nice joke
what the fuck
nope i am so sleepy i am seeing only half coz half of my eyes are closed
🚶
and the task is inside the cog, not in something in the cog, just in the cog
um?
I don't have any left after being up for 31 hours
girl
take me with you 😔 I doubt I'll survive in this hellish paradise

Hmm both options, either way make the bad decision 
smh
If you bring food, I agree 🐒