#discord-bots

1 messages · Page 1140 of 1

slate swan
#

i got this

#

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 troll

#

take ur time

#

I’m back

#

i was bored so i made an ansi builder which i dont even know will work or not

slate swan
#

whats the event called for whne you wanna clear messages

#

pretty cool

#

for example the !clear command

#

whats that event

slate swan
slate swan
unkempt canyonBOT
#

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...
slate swan
#

lemme test it in action first

#

cool

#

okay

#

what about message.delete(amount)

slate swan
#

works finish, except for my choice of colors

#

now i need to add bold & underline

#

Wtf is an ansi sped_pepe

#

one more question

#

read this

#

how do I check if a user has a certain permission

#

like manage messages

unkempt canyonBOT
#
Fat chance.

No documentation found for the requested symbol.

slate swan
unkempt canyonBOT
#

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.
slate swan
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@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").
slate swan
#

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 ""

left idol
#

how do i a, b, c = function()
with an async function?

slate swan
#

add a , and next permissions

slate swan
#

Ok\

slate swan
slate swan
#

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

left idol
#

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}")
slate swan
#

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"

slate swan
fading marlin
fading marlin
fickle hamlet
unkempt canyonBOT
fickle hamlet
#

Change this to false on the command. Then it’ll be counted as disabled.

fading marlin
unkempt canyonBOT
#

@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.
slate swan
#

How can I make it say that you dont have permission to do this command if the user doesnt have that permission

fickle hamlet
fading marlin
fickle hamlet
cloud jolt
#

what discord library are y'all using for bots these days? discord.py still?

fading marlin
#

yes

fickle hamlet
#

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

fading marlin
#

:p

slate swan
slate swan
#

dpy uses a converter for annotations

slate swan
slate swan
#

but i cant say so myself cuz i havent used it lol

fading marlin
slate swan
#

heard from? someone who didn't even touch it?

slate swan
#

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

fading marlin
#

no, foo is just your callback

slate swan
#

callback?

fading marlin
#

maybe that'll clear it up a bit

slate swan
#

Ik

#

Im talking abotu the decorator name tho

slate swan
#

nicee so we can't use decos without codeblock here 😂

slate swan
fading marlin
slate swan
#

and does it have to be under like the command

#

or can it be anywhere on the code

fading marlin
#

it should be in the same file (and class if you're using cogs) where you defined your callback, after you defined it

slate swan
slate swan
#

is automod some set of events?

slate swan
#

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}

slate swan
#

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

slate swan
#

y9su

slate swan
slate swan
#

I tried user=member

#

in the args section and it dindt work

slate swan
slate swan
#
@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.')
slate swan
#

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

slate swan
slate swan
#

So wait

slate swan
#

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.

slate swan
#

hmm

#

Oh yeah.

#

author is the person who called the function?

slate swan
slate swan
slate swan
#

I haven't done anything similar and I kinda wanna see.

#

!d discord.ext.commands.Context.author

unkempt canyonBOT
slate swan
slate swan
#

that's why you wanna typehint stuff

slate swan
unkempt canyonBOT
slate swan
#

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

flint isle
#

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.```
slate swan
slate swan
slate swan
unkempt canyonBOT
#

@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...
slate swan
#

its a deco to register event listeners internally

flint isle
slate swan
#

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.')```
slate swan
#

Whenever someone says .clear 5 without the permission

#

it gives that error

#

and it says 1 pos only but 2 were gfiven

flint isle
slate swan
#

ctx, error?

slate swan
#

and that makes sure what happens

#

tOhh

#

the error that was raised

cloud jolt
#

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?

slate swan
#
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
slate swan
#

as sarth showed you need to reassign the value of a global variable

#

so in this case automod

slate swan
slate swan
slate swan
slate swan
slate swan
fickle hamlet
unkempt canyonBOT
#

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:
slate swan
#

use run_in_executor instead

#

why thread pools over threads?

fickle hamlet
slate swan
#

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?

slate swan
fading marlin
slate swan
#

I restarted it too

#

this is a cool diagram

#

is there anything wrong with my code

fickle hamlet
slate swan
#

@slate swan ?

scarlet aurora
#

python will never support slash commands?

slate swan
#

nope

scarlet aurora
slate swan
#

python doesnt support slash commands

#

I coulda swore

#

yeah that's what I meant

scarlet aurora
slate swan
#

pleaseee someone help

scarlet aurora
#

So I've been lied to

cloud jolt
#

has anyone connected discord.py to a db for storing settings per server?

slate swan
slate swan
scarlet aurora
#

alr ty

cloud jolt
slate swan
slate swan
slate swan
slate swan
fading marlin
slate swan
#

nvm got it to work

slate swan
# slate swan *executor to use

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

slate swan
#

yep

#

@slate swan like that?

#

like.. what?

slate swan
#

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

slate swan
left idol
#

i believe im doing it correct rarity, name, patk, matk, defense, agt, element, classs, perc = await gacha()

slate swan
#

How do I make it so that it also sends something in the actual discord channel when a user leaves

slate swan
#

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

slate swan
#

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

scarlet aurora
#

how do I do the slash commands?

slate swan
#

Ahh

#

thx

#

no problem, test it out first

uneven sapphire
#

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)```
slate swan
#

can someone help me on a welcome command that will look like this? i have the code. theres no errors it just wont send

slate swan
#

i can show/send it if yu want

uneven sapphire
#

well, just send here, i'll watch.

slate swan
#

alright whats the thing to upload big code?

#

dont wanna mess the whole chat up

uneven sapphire
#

just upload the leave message part

slate swan
unkempt canyonBOT
#

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.

slate swan
#

thats the code

#

error?

uneven sapphire
#

i don't see leave pic creation, it's first

#

also you didn't added to send

slate swan
#

oh didnt send full code

uneven sapphire
#
await ctx.send(file=discord.File('rank.png'))```

here's an example of how to add it to message
slate swan
#

oh wait yes i did i think

#

ah

#

where would that be?

uneven sapphire
#

add a file=discord.File('Yourpicname.png')

#

before text i think

slate swan
#

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

uneven sapphire
slate swan
#

haha

uneven sapphire
#

i think there may be intents problem

#

i had it too

slate swan
#

ah jeez. this hurts me

uneven sapphire
#

well, just try to turn it on.

slate swan
#

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

uneven sapphire
#

it is off by default, you need to turn it on on website and then in code

slate swan
#

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.

slate swan
#

hElp

uneven sapphire
slate swan
#

yes

uneven sapphire
#

well, then idk. For me intents too don't work, so in economy i just put everywhere a checks in database.

slate swan
#

# 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

fading marlin
#

you have to send the embed to the user first before banning/kicking them iirc

slate swan
#

oh

#

oh yea otherwise it wouldnt send because they wouldnt be in the server

fading marlin
#

pretty much, yeah

slate swan
#

could u join my server

#

and help test it

slate swan
#

anyone know how i can make this look better? (dsicord-wise)

#

I keep getting errors

#

For the unban command

#

Does anyone know the issue?

slate swan
#

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

blazing kettle
#

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

steady lynx
#

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)
maiden fable
#

Why not use the lib itself....?

slate swan
#

he cant answer the question🗿

maiden fable
#

!d discord.Webhook.send

unkempt canyonBOT
#
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`.
maiden fable
#

It takes a username kwarg too

slate swan
#

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

winter gull
#

@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}")
slate swan
#

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

winter gull
#

Sure

slate swan
#

alr ill send code

slate swan
# winter gull Sure

so it doesnt get any errors nothing in terminal it just when someone joins it doesnt do anything

maiden fable
winter gull
winter gull
maiden fable
winter gull
#

I don't

maiden fable
#

That unban command is from Lucas

winter gull
#

I saw from a website

maiden fable
#

Then don't follow the website (:

winter gull
#

noted 🗒️

slate swan
#

and didnt think it would do anything and it didnt

winter gull
#

Are you putting a channel ID in get_channel() ?

flint isle
#

[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
winter gull
winter gull
unkempt canyonBOT
#

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.

slate swan
#

but ill find another way probably

winter gull
#

Try putting the server Id, and the variable will have a list of channels. That's my guess

flint isle
slate swan
winter gull
#

Uhhh

#

@slate swan try running this


channel = client.get_channel(<id>)

@client.event
async def on_ready():
    await channel.send('ready')
torn sail
#

You need to get the channel within the event

slate swan
#

yeah

#

def*

#

there

scenic grove
slate swan
#

to the welcome channel from channel id

scenic grove
#

also putting that kind of stuff in on_ready function is not a very good practice as i heard

shrewd apex
#

yes

slate swan
#

wasnt me

scenic grove
#

it might just doesnt work

shrewd apex
#

just a print is enough

shrewd apex
#

it will work if channel is defined

#

but not a good practice nevertheless

slate swan
#

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

shrewd apex
#
channel = client.get_channel(id) or await client.fetch_channel(id)
slate swan
#

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

slate swan
#

Is there a way to make a command to add other commands?

scenic grove
#

ofc

#

but its complicated and you have to invent the system on your own

slate swan
scenic grove
fading marlin
#

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?

scenic grove
# slate swan what would be a way

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

slate swan
scenic grove
#

there is probably a better way to do it

slate swan
#

i use jishaku and add commands in an eval using bot.add_command.

fading marlin
slate swan
#

any eval tool/command which allows you to access your bot var can help you do that

#

!pip jishaku

unkempt canyonBOT
scenic grove
fading marlin
# slate swan What's that

evaluates or executes python code

>>> result = eval("2 + 2")
>>> print(result)
4
>>> result = exec("print(2 + 2)")  #  'result' would be None
4
scenic grove
slate swan
#

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

scenic grove
#

and it will be more complicated i guess

slate swan
#

like how would the bot know that the dictionary key is a command, the only choice you have is using on_message with that

slate swan
slate swan
scenic grove
#

with that extension seems like you can easily manage that stuff with a few lines of code

slate swan
scenic grove
#

while with json or anything like that you have to implement your own system

slate swan
scenic grove
slate swan
#

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)

slate swan
#

with the command name being the command name you want mb

slate swan
#

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

fading marlin
#

do note that all of the commands that you add will no longer exist once you restart your bot

slate swan
#

as you have been told exec and eval are also usable but that's too unsafe

slate swan
#

i think just a json dictionary will be way easier

scenic grove
slate swan
scenic grove
#

or if he runs bot on his own machine

#

he he he haw

slate swan
#

just create a tag system like R Danny and many other bots have

#

much easier and Efficient than the addcommand thing

fading marlin
scenic grove
#

btw, it might be not a very proper channel, but, how to make text to be a paragraph etc inside those hints?

fading marlin
#

what hints?

slate swan
#

you mean the int and str?

scenic grove
#

mhm

slate swan
#

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?

scenic grove
fading marlin
#

oh, doc strings

fickle hamlet
#

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

slate swan
#
"""
About class

Attributes 
-----------

attr: :class:`type`

"""
``` is how you make the docstrings generally
scenic grove
#

i see, welp thanks

fickle hamlet
#

If your using sphinx you'll need to install the napoleon extension, cause this is a spin-off, hybrid of the google docstyle

slate swan
#

not really, i've been using this in sphinx with just autodoc

fickle hamlet
#

Well, for sphinx 1.3+

slate swan
#

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

slate swan
#

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?

slate swan
#
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

slate swan
#

wait just seen theres a error

slate swan
fading marlin
#

since dpy uses type annotation converters, type hint int to minutes, otherwise it'll return a string instead of an integer

slate swan
#

^ also this

#

another thing, this afk system has a lot of failure

slate swan
slate swan
#

the mention doesnt work

#

imma try to see if i can spaces now

#
  1. if the bot goes offline and a new session starts, it wont care about the old one
  2. 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_context was removed 3 + years ago
#

ah

#

so i shouldntbe using pass_context

fading marlin
#

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

slate swan
#

So how do I add new data to my json dict?

#

!d json.dump

unkempt canyonBOT
#

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.
slate swan
#

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

slate swan
#

no

#

then that wouldn't work.?

#

youre dumping in a json file using that method, not a dictionary

slate swan
#

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)```

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | dont do this.
002 | {'name': 'text'}
slate swan
#

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.

slate swan
#

wait what quotation mark?

#

if its already a string , it is.
you dont need to mess with it

#

like
{"key": "value"}

slate swan
#
@client.command()
async def addcmd(ctx, name, *, text):
    newcmds = get_config("newcmds")
    newcmds[name] = text

like this?

#

hm yeah

hidden snow
#

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

slate swan
vale wing
unkempt canyonBOT
#

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.
hidden snow
#

great ty

unkempt canyonBOT
#

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.
slate swan
#
@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

vale wing
#

No idea I don't use it like that

#

According to docs it should tho

shrewd apex
#

yeah it will work

slate swan
#

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

slate swan
# slate swan 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>

visual island
slate swan
#

those aren't even slash commands overall....

slate swan
#

cause i don't think its discord.py by the command structure

covert basin
#

What is this error?

slate swan
spring flax
#

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))

patent lark
#

i thought discord.Message.author returned the discord.Member object?

visual island
visual island
patent lark
#

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?

spring flax
#

Uh yes

#

Member is a guild member

patent lark
#

right

#

kinda thought so. but my brain died for a minute

exotic eagle
#

@client.command() async def kick(ctx, member : discord.Member): if ctx.member.voice is not None: await member.move_to(None) print("Kicked user.")

spring flax
#

And?

exotic eagle
spring flax
#

Remove ctx.

exotic eagle
#

anyone know why im getting Attribute Error: 'Context' object has no attribute 'member'

spring flax
#

if member.voice is not None

haughty echo
#
ctx.guild.roles.count
``` this is correct?
spring flax
#

guild.roles returns a list

#

You can call len() on that

haughty echo
#

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()

spring flax
#

What code did you use?

haughty echo
#

means?

#

i am using nextcord

spring flax
#

What line of code did you put in?

spring flax
haughty echo
#

len(ctx.guild.roles.count)

spring flax
#

Remove the .count at the end

haughty echo
#

len(ctx.guild.roles)

#

like this?

#

done thx

vale sierra
#

no because there isn't any > operand, i just want to convert a str into an int

placid skiff
vale sierra
#

nothing in the console, you don't help me you make the thing more difficult

paper sluice
#

exec("try: val=int(val)\nexcept ValueError: print('no')")

slate swan
#

ew

paper sluice
placid skiff
# slate swan ** **
string = "1 2 3 4 5 $"
val = int(''.join(char for char in string if char.isalnum() and char.upper()==char.lower()))
placid skiff
slate swan
#

s1 = await client.wait_for('message')
s1 = s1.content
s1=int(s1)

ValueError: invalid literal for int() with base 10: ''

help me pls

placid skiff
#

Lol read the message above we have discussed that 'til now

vocal snow
slate swan
#

👁️ 👁️

placid skiff
#

Ashley shared a weird way to do that so i shared a way even more weird D_D

slate swan
placid skiff
#

oh no sad_ass

slate swan
#

this hurts me more than it hurts you😡

tawdry canyon
#

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')`

placid skiff
#

!d discord.Embed

unkempt canyonBOT
#

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`.
tawdry canyon
#

ty

paper sluice
slate swan
#

using regex smh

slate swan
paper sluice
#

quickest algorithm to convert str to int implemented in c, sounds good 😄

slate swan
robust fulcrum
#

@paper sluice

#

Still this error

paper sluice
#

thats my name, yes

robust fulcrum
#

I removed the commit

paper sluice
#

create the table lol

robust fulcrum
#

I created

paper sluice
#

open the sql terminal, and check if the table exists

robust fulcrum
#
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()
robust fulcrum
paper sluice
#

hmm hold on

vocal snow
#

why are you committing after a SELECT 🤔

fair summit
#

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

slate swan
vocal snow
slate swan
#

💀

#

i just wokeup for that 💀

vocal snow
#

Good morning okimii

paper sluice
paper sluice
slate swan
slate swan
slate swan
slate swan
#

🧑‍🌾

paper sluice
paper sluice
slate swan
#

red head moment

slate swan
paper sluice
haughty echo
#

{str(len({m.id for m in bot.get_all_user() if m.status is not nextcord.Status.offline}))} this is correct?

fair summit
#

sorry if it is a dumb question, but i am not familiar with that

paper sluice
haughty echo
# paper sluice 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'
paper sluice
#

what is get_all_user?

haughty echo
#

online users

robust fulcrum
#

What should I do now?

paper sluice
vocal snow
paper sluice
#

directly via sqlite terminal or something

robust fulcrum
#

I don't have terminal

#

On mobile

paper sluice
#

sad

robust fulcrum
#

😢

vocal snow
#

why are you on mobile 😭

slate swan
#

why not bro

robust fulcrum
vocal snow
#

YES

robust fulcrum
#

Not to me

tawdry canyon
#

does anyone know why this is happening?

paper sluice
tawdry canyon
#

here is my code

vocal snow
robust fulcrum
paper sluice
robust fulcrum
#

Bruh

#

I already there

paper sluice
#

then ask there....

slate swan
paper sluice
#

RESTToken

tawdry canyon
slate swan
#

good

tawdry canyon
#

thats like from ages ago

tawdry canyon
vocal snow
#

!tags positional-keyword

unkempt canyonBOT
#

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)

tawdry canyon
#

the same is still happening but i changed the variable name

#

idk what to do

tawdry canyon
#

what is kwarg

vocal snow
#

keyword argument

tawdry canyon
#

oh

#

srry

vocal snow
#

the kwarg is embed so you would do embed=quote

tawdry canyon
#

k im still confused but its probably fine

#

ill just do a normal message

robust fulcrum
vocal snow
shrewd apex
#

how to remove old commits from pycharm vcs

vocal snow
#

whats a vcs

shrewd apex
#

i added an commit b4 didn't push then added a few new commits

#

version control

vocal snow
#

ah

shrewd apex
#

now the prev commit was like a 1gb file which i commited by mistake and now it's not letting me push

#

;-;

robust fulcrum
#

How can i check that a cell is empty?

vocal snow
#

empty as in Null?

robust fulcrum
#

I want to check that cell is null or not

#

How to?

robust fulcrum
vocal snow
#

in SQL or python

robust fulcrum
unkempt canyonBOT
robust fulcrum
#

This

stray carbon
#
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-

shrewd apex
#

nvm i got it pushed now

stray carbon
#

what?

vocal snow
paper sluice
flat solstice
#

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)

slate swan
flat solstice
flat solstice
shrewd apex
#

is there any way to find the time in locale of a user?

robust fulcrum
shy haven
#

!pip pywin32

unkempt canyonBOT
shy haven
#

!pip keyboard

unkempt canyonBOT
robust fulcrum
#

@slate swan

#

Can you help me at code?

slate swan
#

hm*

robust fulcrum
#
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?

slate swan
#

I'm out, I'll point out a nice amount of mistakes and I'll get sued

robust fulcrum
#

Anyway tell me mistakes

#

I'll try make it best code

#

And I'll try my full best

slate swan
#

mhm

robust fulcrum
#

Hmmm

spring flax
#

Use the aiosqlite context manager when doing operations

#

!pypi aiosqlite

unkempt canyonBOT
spring flax
#

Examples (I think) are there

slate swan
robust fulcrum
#

Idk what's context manager

robust fulcrum
spring flax
# slate swan excuse me? that's what they are using?

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?

slate swan
# robust fulcrum ```py import aiosqlite import discord from discord.ext import commands import as...
  • Don't connect to the database every time a message is sent. In essence, don't connect to the database in the get_prefix function 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 (id in get_prefix)
  • Don't use try and finally, instead use a conditional or a simple or statement -> return prefix or '@'
  • Don't close the connection in the connect function, rather use the same connection everywhere (in get_prefix too)
#

there are more errors in the set_prefix command

robust fulcrum
#

Can I ask one thing?

slate swan
#

Don't connect to the database on each command invocation, You don't need to SELECT to update

slate swan
robust fulcrum
#

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?

slate swan
#

subclass the bot class easy

robust fulcrum
#

Bruh

#

If i would subclass the get_prefic would be at top

placid skiff
#

get_prefix is not even a class how would you subclass that D_D

robust fulcrum
#

Bruh

slate swan
#

use brain

robust fulcrum
#

😫

slate swan
robust fulcrum
#

Let me subclass

#

I'll tell when i done

placid skiff
#

i was answering to him ashley D_D

#

and i read wrong his message D_D

slate swan
#

!e


class Foo:
 def _alias(self):
    self.not_alias()
 def not_alias(self):
    print("Ashley is so uwu")

Foo()._alias()
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

Ashley is so uwu
dense coral
#

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.

full valley
#

Whats the best way to make a timed mute command?

#

Is asyncio.sleep() alright for 30 days?

spring flax
#

just consider discord timeouts

full valley
#

yeah thats what I was thinking, is it worth doing it via a database

spring flax
#

why do you need a database?

full valley
#

How else would I store the mute information for a member?

spring flax
unkempt canyonBOT
#

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").
lament mesa
#

a db isn't necessary if you're using timeouts

spring flax
full valley
#

Right but im wanting it more of a role, not timeout

spring flax
#

but why?

full valley
#

Because its channel specific

spring flax
#

oh hmm

dense coral
spring flax
lament mesa
spring flax
#

so you want to log the mute information? For like a command that shows all the member's mutes?

full valley
#

All active mutes, how long each mute has left, etc.

dense coral
full valley
#

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

spring flax
spring flax
#

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.

lament mesa
spring flax
full valley
#

how often you think for the task loop

dense coral
lament mesa
#

use asyncio.sleep to unmute when the bot is online

spring flax
#

use logic of, for example, if mute_time >= time_now

full valley
#

so yeah db with timedeltas and loop to check those could be better?

spring flax
#

yes, don't use asyncio.sleep

full valley
#

how long should I loop for each check?

slate swan
#

Why do I get runtimeerrors whenever i end the script? How do I prevent this from happening

spring flax
#

you mean how often to loop?

full valley
#

yes

lament mesa
spring flax
#

why use both? I would suggest one

lament mesa
#

and this method prevents some issues when using tasks.loop

spring flax
#

what are the issues with tasks.loop?

full valley
lament mesa
spring flax
#

yeah, when the mute command is done, why input all the other information except the mute duration and use asyncio.sleep for the unmutes

full valley
#

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?

lament mesa
#

yeah

sick panther
#

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.
slate swan
#
async def main():
    async with LateNightModeration() as bot:
        await bot.start()

asyncio.run(main())
``` replacing bot.run() with this will trigger the on_ready
robust fulcrum
# slate swan subclass the bot class easy
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?

slate swan
sick panther
hallow obsidian
#

guys where can I ask my questions about my code

robust fulcrum
slate swan
slate swan
slate swan
robust fulcrum
#

Actually my code was trash

#

So Ashley told me to subclass bot

#

So i asking now where should I do setup hook code

slate swan
#

as i said, in the botclass, with the same indentation as your init dunder

robust fulcrum
#

Ok

slate swan
#

what do you not understand in it?

robust fulcrum
#

I understood

shy haven
#

!pip pyautogui

unkempt canyonBOT
#

PyAutoGUI lets Python control the mouse and keyboard, and other GUI automation tasks. For Windows, macOS, and Linux, on Python 3 and 2.

robust fulcrum
#

?

slate swan
robust fulcrum
#

Oh k

#

Me do

slate swan
#

the docstrings are cursed enuf to ruin my day

shy haven
#

!pip pymsgbox

unkempt canyonBOT
#

A simple, cross-platform, pure Python module for JavaScript-like message boxes.

robust fulcrum
#

?

slate swan
robust fulcrum
#

Why using commands here?

shy haven
#

o

#

wrong channel sry

slate swan
robust fulcrum
#

@slate swan will it be self.bot.connect = "connection here"
Or bot.connect = "bruh"

slate swan
#

both are wrong

#

it will be self.connect = "..." because self is your bot class

robust fulcrum
#

Oh k

#

OOPS hard for me

robust fulcrum
slate swan
#

yes it is

#

you can also do self.connect = await aiosqlite.connect(...)

sick panther
slate swan
sick panther
#

I got 2.0 from the github, I cloned the repo

slate swan
#

if you installed discord.py 2.0 in replit using pip, thats your issue

#

did you use pip?

sick panther
#

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

slate swan
#

yeah it works, but only for one time.

#
poetry add git+https://github.com/Rapptz/discord.py``` use this cmd
sick panther
#

This will take years

slate swan
#

replit being replit, takes barely 13 seconds on a local device

sick panther
sick panther
slate swan
sick panther
#

Ah, it was os.environ just got confused for a second, my bad

slate swan
#

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

sick panther
#

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

slate swan
#

the worst advice 💀

sage otter
#

Block that person

sick panther
#

Will do, thanks for the advice

slate swan
#

the only thing i like about replit is the multiplayer and enforcing poetry 😻

#

nothing good for hosting purpose tho

sick panther
slate swan
#

i agree, tho i use VSCODE live share

sick panther
#

Never heard of that

maiden fable
sick panther
maiden fable
#

You're welcome

spring flax
#

Is maintaing a forked dpy library yourself hard, specifically adding the new discord features to the lib

#

Huh?

slate swan
maiden fable
spring flax
#

we?

#

Ws*?

vale sierra
slate swan
vale sierra
slate swan
slate swan
maiden fable
heady sluice
#

please be more patient with the helpers

#

furthermore, this is not the appropriate channel to learn python basics

vale sierra
heady sluice
#

nice

vale sierra
#

that's it and he continue to ping me even if i say its finished

heady sluice
#

great 👍

#

yeah you can use tasks

#

just set hours to 4 in the deco

slate swan
#

!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)
unkempt canyonBOT
#

@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'
heady sluice
#

ew

#

respect classes

slate swan
#

no

vale sierra
heady sluice
#

yes

#

and you start them in the init of the cog

#

not sure what you mean by that

slate swan
#
class cog(Cog):
  @tasks.loop(...)
  async def _(...):
    ...
#

meh: ew

heady sluice
#

why would it be ew

worthy wagon
#

(no homo)

slate swan
#

love you too

heady sluice
#

even if you pep8n't

#

at least no uwu

slate swan
cloud dawn
#

What did I just run into 🐒

slate swan
#

us

heady sluice
#

I'll just start saying ewu when Ashley says uwu

#

that's more self-explanatory

slate swan
#

lovely

shrewd apex
#

👁️

cloud dawn
#

Why is ash in such a good mood tf

shrewd apex
#

wrong eyes

slate swan
heady sluice
heady sluice
slate swan
heady sluice
#

what the fuck

shrewd apex
heady sluice
#

no

#

the init is in the cog

#

not inside the task of the cog

cloud dawn
heady sluice
#

and the task is inside the cog, not in something in the cog, just in the cog

slate swan
#

um?

worthy wagon
#

I don't have any left after being up for 31 hours

heady sluice
#

girl

slate swan
heady sluice
cloud dawn
slate swan
#

smh

cloud dawn
#

If you bring food, I agree 🐒