#discord-bots

1 messages · Page 844 of 1

weary sierra
#

What this mean? And how can I fix it?

slate swan
#

I mean, people get themselves roasted rofl

slim ibex
#

an indice has to be a number, not a str

#

for example

kindred epoch
#

why are you fetching the member when you already have a member obj of them

weary sierra
#

servers.data[10]?

kindred epoch
weary sierra
#

I barely know Python ☠️

slate swan
# weary sierra

First of all, dont use servers as a variable name since its already a Command name and may cause errors, second of all, servers is a list

kindred epoch
#

dud making a bot without knowing python is pretty bad

weary sierra
#

Connected with the API

slim ibex
#

!e

my_list = ["hello", "world"]

try:
  print(my_list[0])
  print(my_list["hello"])
except TypeError as e:
  print(e)
unkempt canyonBOT
#

@slim ibex :white_check_mark: Your eval job has completed with return code 0.

001 | hello
002 | list indices must be integers or slices, not str
slim ibex
#

you see how when i try to access the element by its actual value, it doesn't work

slim ibex
calm vortex
weary sierra
cold sonnet
#

heh

slate swan
#

!e
lst = ["Hunter", "uwu"]
print(lst[lst.index("uwu"])

pliant gulch
# slate swan .index exists

Except that is support in-efficient compared to hash maps, as list.index(x) is O(n) whilst with dict's their getitem is O(1)

slim ibex
#

💀

slate swan
slim ibex
slate swan
#

!e

lst = ["Hunter", "uwu"]
print(lst[lst.index("uwu")])
#please make it work```
unkempt canyonBOT
#

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

uwu
cold sonnet
#

what are big o problems

slate swan
#

Ye

slim ibex
#

finding the time complexity of some code

cold sonnet
#

oh nice

cold sonnet
#

and how do you do that

pliant gulch
#

Usually it's very easy to guess the time complexity

#

Sometimes it's a bit harder, such as len(sequence)

slim ibex
#

i found out today that you can actually remove all the constants and look at the biggest term to find the time complexity

pliant gulch
#

len() on builtin sequences are almost always O(1)

slim ibex
#

because the constant gives you the EXACT time complexity, but we just want to see what it will usually be

pliant gulch
#

But depends on the implementation of __len__

manic wing
dull terrace
#

i think so onii

slate swan
#

!f-strings exist

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

manic wing
# manic wing

how do you guys suggest I make it so users can choose where to place a number?

slim ibex
#

i have this one recursive one where I calculate the complexity of it

dull terrace
#

isnt get_friends_count a integer though

slate swan
slim ibex
#

why are you passing an ID to get_bans?

#

is that the guild id?

manic wing
slim ibex
#

you just need to loop through the guild bans, and see if the user's name and discriminator is equal to the member parameters name and discriminator

hoary cargo
manic wing
#

?

slate swan
pliant gulch
slim ibex
#

as in:

banned_users = await ctx.guild.bans()

for banned_user in banned_users:
  user = banned_user.user

# some conditional to check if the user name and discriminator is equal to the member name and discriminator
dull terrace
#

i haven't even heard the term time complexity before

cold sonnet
slate swan
cold sonnet
#

indeed

slate swan
#

Oh Developer is here

royal meteor
#

Does @unkempt canyon have an invite link? If so where can I find it?

slim ibex
slate swan
#

And its not the appropriate channel

royal meteor
hoary cargo
slate swan
slate swan
cold sonnet
slate swan
slim ibex
#

yes i am

#

my about me says so

cold sonnet
#

I respect it

hoary cargo
slate swan
#

@slim ibex wao you were binds all this time, and you sure you 14?

slate swan
cold sonnet
#

my birthday picker works with two dropdowns in one view

#

and you'd vomit seeing my code

slim ibex
slate swan
dull terrace
#

hmm okay

kindred epoch
slate swan
slim ibex
#

bro everyone thinks im older than i am

pliant gulch
#

👀

cold sonnet
slate swan
unkempt canyonBOT
slate swan
hoary cargo
cold sonnet
slate swan
hoary cargo
hoary cargo
#

MR_uncanny_1 my server bot uses dpy 1.6.0

cold sonnet
#

not even 1.7

slate swan
cold sonnet
#

don't you like get nitro

#

for free

#

cuz of gender equality

hoary cargo
#

lmao

slate swan
cold sonnet
#

mk

kindred epoch
slate swan
cold sonnet
#

me: aaaa

slate swan
cold sonnet
unkempt canyonBOT
hoary cargo
slate swan
slate swan
hoary cargo
# cold sonnet not even 1.7

FeelsOldMan the code is quite old, i mean i still sometimes modify things like add new banned words in the list but never actually started to rewrite it from 0

slate swan
unkempt canyonBOT
cold sonnet
slate swan
cold sonnet
#

noob

slate swan
cold sonnet
slate swan
slate swan
slate swan
cold sonnet
#

you're off-topic

slate swan
#

I'm out

cold sonnet
#

to an ot channel?

slate swan
#

maybe

slate swan
cold sonnet
#

chill

slate swan
haughty quartz
#

is there a way for me to get a userinput arg and a member arg?

cold sonnet
#

async def command(ctx, userinput, member)?

#

don't quite understand

haughty quartz
#

ill try that

hoary cargo
cold sonnet
#

might typehint member to Member

haughty quartz
cold sonnet
#

yes

#

I just like to import it

slim ibex
slate swan
hoary cargo
haughty quartz
cold sonnet
#

how

slim ibex
#

aka the input() function?

hoary cargo
#

never seen someone to import member

haughty quartz
#

nah not really !pb myinput member

slim ibex
unkempt canyonBOT
#
The Zen of Python (line 2):

Simple is better than complex.

slim ibex
#

!zen 1

hoary cargo
#

true

unkempt canyonBOT
#
The Zen of Python (line 1):

Explicit is better than implicit.

slim ibex
#

i meant to do the explicit is better than implicit

#

but i guess both work

haughty quartz
hoary cargo
slim ibex
#

mhmm

pliant gulch
#

Unless you do it wrong

slate swan
hoary cargo
#

MR_uncanny_1 right

hoary cargo
# unkempt canyon

watch the oneliners write a 20m spaghetti be like "bro trust me this is better"

slate swan
#

btw is there a way that can chnge the cooldown from 50 to 30

slate swan
slate swan
cold sonnet
#

sharing your opinion about coding

#

unfortunately, your opinion is bad

hoary cargo
#

music stops

slate swan
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
slate swan
cold sonnet
#

even tho you're ot rn

slate swan
hoary cargo
#

ot this ot that what about just stop MR_uncanny_1

slate swan
#

ion think i can update the per param in the cooldown, i only found update_rate_limit

#

i believe that update_rate_limit updates the rate parm

slate swan
kindred epoch
#

what are you saying

slate swan
slate swan
kindred epoch
#

ye it works fine for me

slate swan
kindred epoch
#

you said i dont think i can update the per param in the cooldown, but you can

kindred epoch
#

no

slate swan
kindred epoch
#

what are you trying to do

slate swan
slate swan
#

they are tryna update the per parameter which u just said they can do so where’s the confusion?

slate swan
#

yk wut im trying to do right?

kindred epoch
#

well update_rate_limit changes the rate param

slate swan
kindred epoch
slate swan
kindred epoch
slate swan
#

Dynamic cooldown exists?

#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
naive spoke
#

here is my code

@client.command()
async def test(ctx):
  message =  await ctx.send('click here for roles')
  await message.add_reaction('✅')
  await ctx.send('giving role to'f'{ctx.author.name} ')

and when i used the command it says both of the outputs but i want it to only say to the person who clicked the reaction

naive spoke
#

whats that

slate swan
#

Also, you have some pretty f-strings

slate swan
unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

It waits for the event to take place

kindred epoch
slate swan
naive spoke
cold sonnet
#

wait_for is really just the most complicated function of the bot

#

hate it so much

slate swan
kindred epoch
cold sonnet
slate swan
cold sonnet
#

brirl

#

no

naive spoke
slate swan
kindred epoch
slate swan
cold sonnet
slate swan
kindred epoch
#

theres a whole list of events in the docs which you can look into

kindred epoch
cold sonnet
slate swan
kindred epoch
cold sonnet
#

you still need it sometimes

slate swan
unkempt canyonBOT
cold sonnet
#

for example: which year were you born in?

slate swan
cold sonnet
#

unless you make like a half-calculator

#

without the calculator part

kindred epoch
#

either everyone uses disnake or pycord or nextcord or d.py 2.0

naive spoke
cold sonnet
#

seems to tell you exactly what to do

slim ibex
#

lmao

kindred epoch
naive spoke
kindred epoch
naive spoke
kindred epoch
#

the full thing is await bot.wait_for("reaction_add")

naive spoke
#

oh ok

#

ill try

#

this is my code now

@client.command()
async def test(ctx):
  message =  await ctx.send('click here for roles')
  await message.add_reaction('✅')
  await client.wait_for("reaction_add")
  await ctx.send('giving role to'f'{ctx.author.name} ')

and i dont even click anything it just says that immediately

kindred epoch
#

uh wait

#

forgot, you have to add a check in order to check if the reaction was clicked

#

so add ```py
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '✅'

and then edit the wait_for to this
```py
await client.wait_for("reaction_add",check=check)
kindred epoch
#

checks if the reaction is the reaction you want, if it is then the rest of the code will execute

potent spear
kindred epoch
#

?

potent spear
kindred epoch
#

and why not emojis?

potent spear
#

messed up for some text editors ig

slate swan
#

Do y’all recommend using pycord making a bot as a new bot developer?

naive spoke
#

now i get this
Exception has occurred: TypeError
Callback must be a coroutine.
File "C:\Users\a\OneDrive\Desktop\discord bot\my_bot.py", line 53, in <module>
@client.command()

kindred epoch
kindred epoch
slate swan
kindred epoch
#

why do you need tutorials?

#

docs exist

slate swan
#

Ig

hoary cargo
hoary cargo
slate swan
#

Docs just confusing sometimes but yea probably cuz im new to this whole python thing

hoary cargo
#

and join their support server, they most of the times help you

slate swan
#

Alright

hoary cargo
#

so why would you even need youtube videos or something lol

#

and most of the fork videos like pycord works on disnake also

kindred epoch
#

and disnake is way ahead of them

#

in lib updating and stuff

slate swan
#

Idk this stuff confuses me but ill get it one day 😂

hoary cargo
#

i really wanted to switch to pycord but when i've seen their attitude and stuff MR_uncanny_1

hoary cargo
scarlet rune
#

Do bots not catch custom errors using on_command_error or except?

slate swan
#

Ohh

hoary cargo
#

custom error?
maybe custom error handler/ per command

#

if you don't have one, the error will be redirected to on_command_error and it will handle it, this if you have that exact error, else it will raise it in terminal

slim ibex
#

you can create custom exceptions, if that is what you mean

scarlet rune
#
def is_admin():
    async def predicate(context: commands.Context) -> bool:
        with open("settings.json") as file:
            config = json.load(file)
        if context.author.id not in config["owner"]:
            raise initiator.ExecutorNotEligible
        return True

    return commands.check(predicate)```
I thought i can catch ``initiator.ExcecutorNotEligible`` using exceptions or ifinstance
#

the command works when the executor have required permissions but when they don't it just shows the error in terminal

#
    except initiator.ExecutorNotEligible as e:
        print(e)
        bot.send("You are not allowed to use this command.")``` does this not work?
#

making error handler per command would be easier but maybe this would be useful

slim ibex
#

the predicate function doesn’t have to be async btw

scarlet rune
#

do i have to use commands.CheckFailure?

potent spear
#
if context.author.id not in config["owner"]:
            raise initiator.ExecutorNotEligible
return True```
could just be
```py
return context.author.id in config["owner"]```
#

you can handle the check returning False in other ways

slim ibex
#

instead of raising your custom exception, whatever it is, you could raise commands.NotOwner(). What is this ExecutorNotEligible exception?

scarlet rune
slim ibex
#

What is this ExecutorNotEligible exception?

scarlet rune
#
class ExecutorNotEligible(Exception):
    def __init__(self, message="Initiator lacks permission."):
        self.message = message
        super().__init__(self.message)
scarlet rune
potent spear
slim ibex
scarlet rune
slim ibex
scarlet rune
# slim ibex Where is the rest of this function?
class tests(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    try:
        # test
        @commands.command()
        @security.is_admin()
        async def test(self, ctx):
            await ctx.reply("Function executed.")
            print("function tested;")

    except initiator.ExecutorNotEligible as e:
        print(e)
        bot.send("You are not allowed to use this command.")


def setup(bot):
    bot.add_cog(tests(bot))```
slim ibex
#

ctx.send, not bot.send?

slate swan
#

That isn't how this works. Can you please rephrase again what your goal is?

slim ibex
#

commands.Bot doesn’t have a send method

slate swan
#

Also, Bot.send() doesn't exist, and any method like that has been deprecated and removed for a long while.

scarlet rune
rare saddle
#

How to display errors for slash commands? If a person does not have rights

slim ibex
scarlet rune
slate swan
#

Do you have several commands that will share this permission checker? If so, are they all in the same Cog?

rare saddle
scarlet rune
#

it's still one

#

just tryna make my terminal clean

scarlet rune
slate swan
#

If they are all in the same Cog, you can implement a cog_check method to your Cog class that will act as a custom check for any commands under that Cog.

slim ibex
#

!d disnake.disnake.ext.commands.on_slash_command_error

unkempt canyonBOT
#

disnake.ext.commands.on_slash_command_error(inter, error)```
An error handler that is called when an error is raised inside a slash command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_slash_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.on_slash_command_error "disnake.ext.commands.Bot.on_slash_command_error")).
slim ibex
#

@rare saddle

green bluff
rare saddle
green bluff
#

help?

scarlet rune
#

!d discord.ext.commands.Cog.cog_check

unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
rare saddle
slate swan
#

@scarlet rune An example:

from discord.ext.commands import Cog, Context, command


class MyCog(Cog):
    def cog_check(ctx: Context) -> bool:
        ...

    @command(...)
    async def foo(ctx, ...): ...
    # This command will only execute if MyCog.cog_check() returns True.
scarlet rune
slate swan
#

!d discord.ext.commands.Cog.cog_command_error

unkempt canyonBOT
#

await cog_command_error(ctx, error)```
A special method that is called whenever an error is dispatched inside this cog.

This is similar to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") except only applying to the commands inside this cog.

This **must** be a coroutine.
slate swan
scarlet rune
#

forget it i don't do that either

#

let me try

rare saddle
slim ibex
#

np

scarlet rune
slate swan
#

What about it is strange?

slate swan
kindred epoch
#

.command has more features than using on_message as a command

scarlet rune
#

i just want to get rid of this error in my terminal

    raise initiator.ExecutorNotEligible
initiator.ExecutorNotEligible: Initiator lacks permission.
slate swan
#

Wait... It says on_message

hoary cargo
slim ibex
#

lmao

kindred epoch
#

dud lmao are you going to make commands which dont take any args?

slate swan
kindred epoch
#

exactly

vivid marsh
#

Are slash commands a pain in the ass to implement or not really?

kindred epoch
#

with .command it will be way easier

scarlet rune
#
        if isinstance(error, initiator.ExecutorNotEligible):
            return await ctx.reply("No perms.", mention_author=False)```
slim ibex
slate swan
#

I apologize for not possessing the ability to read minds, please show your full code

native wedge
#

How do i load cogs in different folders?

scarlet rune
slim ibex
slate swan
vivid marsh
slate swan
#

People mostly get in trouble by using interaction followups before the response

hoary cargo
slate swan
#

It's really not that bad.

vivid marsh
#

It’s not tbh I hate the slash commands but they don’t look bad

vivid marsh
hoary cargo
#

the pain it will start when you will use buttons, views, select menus and other stuff like this MR_uncanny_1

pliant gulch
#

😔

scarlet rune
vivid marsh
slim ibex
hoary cargo
vivid marsh
#

I already don’t really like using / commands in general and buttons are just even worse

slim ibex
#
@attr.s
class Infraction:
    id: int = attr.ib(converter=int)
    member_id: int = attr.ib(converter=int)
    issuer_id: int = attr.ib(converter=int)
    type: InfractionType = attr.ib(converter=InfractionType)
    reason: Optional[str] = attr.ib(converter=str)
    issue_date: datetime = attr.ib(converter=datetime)
    expiry_date: Optional[datetime] = None
    expired: Optional[bool] = False

attr > dataclass

hoary cargo
#

buttons are nice from the user side to use

slate swan
vivid marsh
hoary cargo
#

well, just to display a button is not hard, depends what stuff you want to attach to that button

hushed galleon
vivid marsh
pliant gulch
slate swan
#

@scarlet rune You can't raise your "own" error in a check like that, it propagates to Client.on_error. You exception class should inherit from commands.CommandError so that you're able to handle it in on_command_error or whatever it is.

#
# Wrong
class MyError: ...

def check(ctx):
    # This won't work, it will be handled by Client.on_error() since it's seen as a non command related error
    if not condition:
        raise MyError(...)
from discord.ext.commands import CommandError


class MyError(CommandError): ...

def check(ctx):
    # This error is treated as a command error and can be handled in a command error handler
    if not condition:
         raise MyError(...)
#

!d discord.ext.commands.CommandError

unkempt canyonBOT
#

exception discord.ext.commands.CommandError(message=None, *args)```
The base exception type for all command related errors.

This inherits from [`discord.DiscordException`](https://discordpy.readthedocs.io/en/master/api.html#discord.DiscordException "discord.DiscordException").

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
hushed galleon
#

their error did say it happened in on_message though

slate swan
#

Which is what I was talking about. Client.on_error saw it as an error that occured in an on_message event.

hushed galleon
#

oh nvm yeah it does display that for improper check errors

#

just couldnt tell that their error did come from a check tho since it was shortened

scarlet rune
native wedge
#

how to load cogs inside folders?

kindred epoch
native wedge
#

ty

visual island
#

!d discord.Member.is_on_mobile

unkempt canyonBOT
#

is_on_mobile()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): A helper function that determines if a member is active on a mobile device.
visual island
#

basically just checking if "mobile" in member's statuses

native wedge
#

what are all the permissions for commands?

#

i know there is for roles, role id, is owner

#

is there more?

pliant gulch
#

It's not really possible to differentiate whether someone is using the desktop or the web browser, as the desktop client uses electron, which is basically still the web version, just on your desktop and in an application

pliant gulch
final iron
#

Why is discord.Member.is_on_mobile a method and not an attr?

pliant gulch
#

What do you mean by optimisations

final iron
visual island
final iron
#

No

#

!d discord.Member.is_on_mobile

unkempt canyonBOT
#

is_on_mobile()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): A helper function that determines if a member is active on a mobile device.
visual island
#

oh

pliant gulch
#

Ah, so you mean that on mobiles users won't be able to see a photo that desktop can see?

visual island
dusk heron
#

@pulsar goblet sorry for not answering, I was eating. but for the print type client, is it just writing the code print(type(client)) ? if so it didn't print anything.

slate swan
#

I don't understand why commands.BadInviteArgument is named as such instead of commands.InviteNotFound but just human nature coming into play I guess.

slate swan
pliant gulch
#

Usually there is a work-around, for an example. This issue I was referring to, could be fixed in on swoop via embedding an attachment into an embed, thus allowing both desktop and mobile users to see it. Perhaps it's worth it to optimise commands for mobile users

#

This is more so of a QOL thing, I'd only do it if it's not complex

#

Quality of life

final iron
#

Could just be a shortcut like ctx.send instead of ctx.channel.send

vivid marsh
#

Ok so I made a 8ball command and I have it to where it goes Question: Answer: is there a way to make it go

Question:
Answer:

slim ibex
slate swan
#

InteractionResponse.send() doesn't exist I think.

slim ibex
#

!d disnake.ApplicationCommandInteraction.response

unkempt canyonBOT
final iron
slim ibex
#

!d disnake.InteractionResponse.pong 🗿

unkempt canyonBOT
#

await pong()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Pongs the ping interaction.

This should rarely be used.
visual island
#

If the interaction hasn’t been responded to yet, this method will call response.send_message. Otherwise, it will call followup.send.

slim ibex
#

andy is here

slate swan
#

InteractionResponse.send_message() will fail if the interaction has already been responded to. Interaction.send() checks for this and does a followup. That's the difference.

pliant gulch
visual island
#

interaction.send() will call interaction.response.send_message() (respond to the interaction) if the interaction hasn't been responded yet. If it's responded, then it will callinteraction.followup.send() (webhook)

#

that's the main thing

#

interaction.response.send_message() by this method

#

that method responds to an interaction

pliant gulch
#

Could also be a defer

#

Same with modals

slate swan
#

no

visual island
vivid marsh
#
@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ["It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
    embed=discord.Embed(title="8ball", url="", description="", color=0xFF5733)
    await ctx.send(embed=embed)
    await ctx.send(f'Question: {question}Answer:  {random.choice(responses)}')```

Is there a way to make the response go in the embed? Or is it impossible
visual island
#

cause it's responded already

slate swan
visual island
#

ping?

#

it doesn't exist

pliant gulch
#

You can't even respond with a ping, you can ack a PING interaction type via PONG

#

This is only sent when handling interactions over web anyways

slate swan
visual island
#

also pong should be rarely used - said the docs

pliant gulch
#

With how discord.py is designed there shouldn't even be a chance for the need of pong to be used

visual island
#

sends a webhook and do stuff with it, which doesn't affect your bot's ratelimit

pliant gulch
#

It's all over gateway

visual island
#

it's useful for big bots

vivid marsh
pliant gulch
#

Isn't PING only sent through web handling?

slate swan
#

You guys have heard of satire, right?

vivid marsh
#

Like the answer choices?

slate swan
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, 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.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
slate swan
#

It's missing some stuff, but should give you a general idea

pliant gulch
#

discord could've done a wayyy better job at documenting embeds

slate swan
#

Discord sucks at documenting stuff

pliant gulch
#

Half of the things you need to manually check, like providers etc

#

It was a pain for me

slate swan
#

Their entire API is pretty poorly documented for the scale that it operates at

vivid marsh
#

I know how to use embeds I just don’t understand how to make it pick the random aswell as put the question and answer in the embed

pliant gulch
#

Imagine discord as a graphql API

#

👁️ 👁️

slim ibex
pliant gulch
#

That query builder is gonna be a pain in the ass to build

slim ibex
#

bro the hype around graphql is like nonexistent now

pliant gulch
#

You saw the firebase video too

#

👁️ 👁️

slim ibex
#

wait which one? i did watch a firebase one recently^

slate swan
pliant gulch
#

I would actually be fine with a graphql API, would make large requests super minimal without needing useless shit

slim ibex
pliant gulch
#

But, alas discord is hard at work figuring out what intent to gate next

#

Probably voice, since voice recv

pliant gulch
slate swan
#

God I hope the group behind modelling the slash commands GUI gets fired for their crime against humanity

pliant gulch
#

naw the people who did modals

#

did you see how it fucking works??

#

I'll send a raw payload rq holdon

vivid marsh
slate swan
#

👍 Of course

slim ibex
#

https://www.youtube.com/watch?v=vAoB4VbhRzM i watched this recently, but i do remember watching a video about graphql hype and shit @pliant gulch

Firebase is a suite of tools for building apps on top of Google Cloud Platform. It's most famous for its realtime database, but also includes services for user authentication, serverless computing, push messaging, file storage, and more. https://fireship.io/pro

#databases #tech #100SecondsOfCode

This video is NOT sponsored.

🔗 Resources

Fire...

▶ Play video
slate swan
#

Count on Discord to not have their own public embed visualizer

pliant gulch
# pliant gulch I'll send a raw payload rq holdon
{'title': 'Test', 'custom_id': '78efd6ade79246f68a30979ebfe848d1', 'components': [{'type': 1, 'components': [{'type': 4, 'style': 2, 'label': 'input', 'custom_id': 'cbed10c7028046e98e7e5158fd4a87f0', 'min_length': 0, 'max_length': 4000, 'required': True}]}]}
``` 😔
slate swan
#

nasty

pliant gulch
#

Like wtf, components inside of components

slate swan
#

Do you know Dyno? Well turns out their entire service is a lopsided house of cards

pliant gulch
#

Lmao, I actually hate all this interaction bullshit as a wrapper dev. I got really pissed with how slash commands worked, at one point I even was making my own schematic language to register commands

slate swan
#

I can break shit so easily it's hilarious. It's even more pathetic for them when you realize that they operate at a pretty big scale

pliant gulch
slate swan
#

Lmao I had to read the docs for interactions repeatedly to actually understand it

#

I'm a pretty stupid individual but documentation should not be that confusing

#

I mean why is there so much nested stuff

pliant gulch
#

Well, with how modals look right now, you can tell that they will be adding more than just TextInput

#

The nested stuff is a real pain in the ass though

#

All the models basically connect with each other and it's a pain in the ass

slate swan
#

Working with JSON is already kind of a PITA in Python with all the dict.get() or catching KeyError shit but this just makes it worse

pliant gulch
#

I made a base model to build procedural classes from raw dictionaries

#

Pretty big brain 🧠

#

Classes are still massive though

slate swan
vivid marsh
#

Since discord sucks at answering questions does anyone know if it will be fully / commands or if there will still be prefixes

pliant gulch
slate swan
#

If your bot is under 75 guilds, don't worry about it

vivid marsh
cerulean osprey
#

How could I run a discord bot from my own computer?

slim ibex
#

host?

cerulean osprey
#

If thats the word

slim ibex
#

if you wanna keep it up 24/7, just keep the pc on with the bot running. but that isn't the best

#

host on a vps

cerulean osprey
#

I plan to keep it on 24/7 anyways lol

slim ibex
#

but hosting on your pc isn't a good idea

native wedge
#

what is difference between bot and client

slim ibex
#

bot derives from client. bot also has commands while client doesn't

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
slim ibex
#

in conclusion, use Bot

pliant gulch
#

Some thing's don't make sense to me though

cerulean osprey
pliant gulch
#

Like why does commands.Bot have listen but Client doesn't

#

There should be no reason to not let client have listen

slim ibex
#

but you can extend implementation/functionality in derived classes

pliant gulch
#

At that point you'd use commands.Bot anyways

green bluff
#

i uninstalled

slim ibex
#

?

green bluff
slim ibex
#

oh, just replace discord with pycord

green bluff
#

no i just uninstalled

slim ibex
#

and uninstall discord_components

green bluff
#

oh ok

#

so pycord.Embed

slim ibex
#

and don't use client

green bluff
#

and stuff right

green bluff
slim ibex
#

are you subclassing to create the bot?

#

use Bot

green bluff
#

so replace

#

word client with bot?

slim ibex
#

wait

green bluff
#

in variable

slim ibex
#

wtf pycord's docs

#

why does it still use discord.

#

i would use disnake anyways

final iron
#

Pycord sucks ass

slim ibex
#

^

green bluff
#

so is disnake better

final iron
#

But anyway, they kept the discord namespace

final iron
slim ibex
final iron
#

Ikr

#

So dumb

#

Probably just to help people transition from discord.py to their fork

#

But imo, it just made everything harder

slim ibex
#

legit

final iron
#

I only spit facts

#

💀

hoary cargo
#

SlowPensive pycord devs sucks, they couldn't even change names properly pyllow

dusky ocean
#

yo how do i react to a message with a unicode emoji

final iron
#

😔

hoary cargo
#

:dodgestare:

#

Bruv

#

My discord be lagging

hoary cargo
final iron
#

I still don't like it though

#

Like how do we know if someone is using discord/pycord or any other fork

#

I think 1 thing we can all agree up on was keeping the discord name space was dumb and annoying

hoary cargo
vivid marsh
#

So I made a purge command and I want it to send a message saying how many messages were deleted after but the amount isn’t working

await ctx.channel.send(‘purged (amount) messages’)

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

final iron
#

See your issue?

hoary cargo
final iron
#

!e

amount = "hi mom"
print("this is my cool phrase: (amount)")
print(f"this is my cool phrase: {amount}")
unkempt canyonBOT
#

@final iron :white_check_mark: Your eval job has completed with return code 0.

001 | this is my cool phrase: (amount)
002 | this is my cool phrase: hi mom
vivid marsh
#

ohhhhh ok i get it

#

I didn’t have anything indicating something needed to be done so it just read it as a message

slate swan
#

how do i fix this?? did i install disnake incorrectly

vivid marsh
#

I don’t use disnake but I would try uninstalling it and reinstalling it

final iron
slate swan
final iron
#

Also the bot.run() line shouldn't be indented

final iron
slate swan
#

new to this but im pretty sure

final iron
#

What virtual environment manager do you use

slate swan
#

i have no idea what that is all ik is im using a virtual invironment

final iron
#

How did you create the virtual environment

slate swan
#

python venv env

#

said taht

#

that

cloud dawn
slate swan
#

in terminal

cloud dawn
slate swan
#

could it be because i previously had hikari installed?

final iron
hoary cargo
final iron
#

Ah yes

#

The 5 fps pensive gif

slate swan
#

how do I indent?

supple thorn
supple thorn
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

supple thorn
#

also why are you asking that here in a discord bot channel

slate swan
#

because I was told to come here

supple thorn
#

why

slate swan
#

idk

supple thorn
hoary cargo
#

The question is
By who

supple thorn
#

also that

hoary cargo
slate swan
#

after many attempts i finally fixed my issue🥲

supple thorn
final iron
#

Install it

supple thorn
#

the library

final iron
#

!pypi gl

unkempt canyonBOT
final iron
#

mhm

#

Actually use lowercase

#

idk if pip is case sensitive

hoary cargo
#

stareSuisei2 so you want to eat a bread without actually having it in your bag? dodgestare

hoary cargo
#

Try to import it in lowercase instead of upper
import gl not import GL

slate swan
#

Pip install it first?
Restart vsc if you're using it

cerulean osprey
#

So I've never used .env files on VS code. (So Im not quite sure how to use them lol), what I did was "Key": "<token>" but it doesnt work. Can someone help? ;-;

final iron
#

You don't need a .env on vsc

cerulean osprey
#

Wouldnt it show up on GitHub?

final iron
#

Just store it in a file and don't push it to github

#

Easy, simple

hoary cargo
#

!pypi python-decouple

unkempt canyonBOT
hoary cargo
#

Ngl, I prefer this over dotenv

cerulean osprey
pliant gulch
#

I'm on linux so, I just export blah="..."

final iron
#

idk if its truthful

#

Don't shoot the messenger

hoary cargo
#

I use it and it's goodstareSuisei2

pliant gulch
#

I use 1 & 0 for booleans in env variables

#

Actually, I don't think that changes anything thinking about this, but I can just run int on it and use it inside of an if statement

slate swan
#

Is there a way i could get a message to be sent when someone buys something from my website? I'm guessing Q2Auth but i cant find any good tutorials.. Also what would be a good test hosting for a simple html php website

#

Does the website has SOMe API?

slate swan
#

Is there a way i can separate scripts in visual studio code but have it still in the same file?... Might not make sense but.

#

Python allows you to import Functions, variables and classes from other files

vivid marsh
#
@client.command(name='8ball', description='Let the 8 Ball Choose!\n')
async def _8ball(ctx, question):
    responses = ["It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
    response = random.choice(responses)
    embed=discord.Embed(title="The Magic 8 Ball has Spoken!")
    embed.add_field(name='Question: ', value=f'{question}', inline=True)
    embed.add_field(name='Answer: ', value=f'{response}', inline=False)
    await ctx.send(embed=embed)```
#

It’s all of a sudden only taking one word for question?

#

But I havnt touched anything and it was working perfectly fine earlier

slate swan
#

Because you copied the code and forgot to add the * as a parameter in the function

#

(ctx, *, question):

vivid marsh
slate swan
#

It's completely from Lucas except for the embed, not even the responses are changed

#

Search for you may rely on it here in the search, and you'll know.

slate swan
#

Tutorials are bad, but the way you're implementing the code, it seems like you're on a right path 👌

vivid marsh
#

Yeah I’m not tryna completely copy just watch it use it and go off my resources from what I’ve done before

sick birch
#

and instead of value=f'{question}' you can do value=question, same with value=f'{response}'

vivid marsh
#

And it won’t mess up the embed?

hoary cargo
#

That has nothing to do with the embed

sick birch
vivid marsh
sick birch
#

improving readability

final iron
naive spoke
# kindred epoch show me your whole code now
@client.command()
def check(reaction, user):
    return user == user.author and str(reaction.emoji) == ':white_check_mark:'
async def test(ctx):
  message =  await ctx.send('click here for roles')
  await message.add_reaction(':white_check_mark:')
  await client.wait_for("reaction_add")
  await ctx.send('giving role to'f'{ctx.author.name} ')

sorry i was late

final iron
#

You can just do value=random.choice(responses)

vivid marsh
naive spoke
#

making a reaction command

kindred epoch
#

all i have to say it learn python before making a discord bot

naive spoke
#

yea

#

i learned the basics

#

and i get this error Callback must be a coroutine.

#

on @client.command()

kindred epoch
#

he doesnt know how functions work, the not async funtion is supposed to be under the async funtion and indented.

#

im pretty sure he knows that commands are async functions, so idk why he put the check funtion there instead of just putting it under it

slim ibex
#

what’s happening?

kindred epoch
#

yes

#

hes supposed to use it in the wait_for

dull terrace
#

i actually hate databases so much

#

ugly ass code

stone beacon
#

use sqlalchemy

#

It's pretty neat and isn't hard to learn with a quick 10 minute reading

#

hard coding sql gives me war flashbacks

stone beacon
pliant gulch
#

Tortoise is a good async ORM

slim ibex
dull terrace
#

json took me about 1/3 of the lines

slim ibex
#

still better

pliant gulch
slim ibex
pliant gulch
#

Unless I have to use LEFT and other bullshit 😔

slim ibex
#

I create all my tables and stuff in an sql file

#

And execute that at program runtime

stone beacon
#

Professional programmer

#

I always forget the keywords

slim ibex
#

sql is very easy to remember for me atleast

pliant gulch
#

SQL is almost English 👀

slim ibex
#

^

pliant gulch
#

If you forget the keywords you have like a 80% of guessing them correctly

stone beacon
#

yep that's what I do

#

Although I've shifted more to firebase these days

#

Haven't touched sql in a while

dull terrace
#

what does fetch actually do in sql, is using it multiple times a waste of resources

pliant gulch
#

EdgeDB is looking real nice

slim ibex
#
with org_structure as (
   SELECT id
          , manager_id
   FROM staff_members
   WHERE manager_id IS NULL
   UNION ALL
   SELECT sm.id
          , sm.manager_id
   FROM staff_members sm
   INNER JOIN org_structure os
      ON os.id = sm.manager_id

Amazing code

stone beacon
pliant gulch
#

INNER JOIN 😔

zenith basin
#

hello

slim ibex
#

!d sqlite3.Cursor.fetchone

unkempt canyonBOT
#

fetchone()```
Fetches the next row of a query result set, returning a single sequence, or [`None`](https://docs.python.org/3/library/constants.html#None "None") when no more data is available.
zenith basin
#

does anyone now how to make a rank card

vivid marsh
#

Bruh is it even possible to have a latency command in a cog?

slim ibex
#

Yes

#

I have one in my cog 💀

vivid marsh
#

Ight I’m just stupid ima continue trying

dull terrace
#

which one should i use

green bluff
stone beacon
#

I haven't used dpy in a bit but yes

green bluff
#

where do i put where

zenith basin
#

does anyone now how to make a rank card

green bluff
stone beacon
#

sheesh guess I forgot

slim ibex
#

You’ll have to use the time module

pliant gulch
#

!d discord.ext.commands.Bot.latency

unkempt canyonBOT
#

property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
slim ibex
#

I really hate how people do sql shit procedurally 😢

stone beacon
#

Oh right right .ext

pliant gulch
#

😳 procedural is my game bro

slim ibex
#

like bro

pliant gulch
#

If it’s not scale-able I don’t want it

#

I’ll end up rewriting it five times anyways

slim ibex
#

why do

db = await aiosqlite.connect(...)
cursor = await db.execute('SELECT * FROM some_table')
row = await cursor.fetchone()
rows = await cursor.fetchall()
await cursor.close()
await db.close()

when

async with aiosqlite.connect(...) as db:
    await db.execute("INSERT INTO some_table ...")
    await db.commit()

    async with db.execute("SELECT * FROM some_table") as cursor:
        async for row in cursor:
            ...

exists

#

first one looks so fucking ugly

vivid marsh
# stone beacon I haven't used dpy in a bit but yes

I have it all set up like self is taken in first and everything but it’s saying

module http.client had no at tribute latency

Idk I can’t figure it out lol I’ll prolly just put it back in my main file

stone beacon
#

Send code

pliant gulch
slim ibex
pliant gulch
#

No clue, it’s magic to me

#

I haven’t read the source

slim ibex
#

lmao

stone beacon
#

Honestly, moyai 🗿 is the best standard emoji there is

slim ibex
#

^^^

vivid marsh
#
    async def ping(self, ctx):
        await ctx.send(f'Pong! wow that took {round(client.latency * 1000)}ms')```
slim ibex
#

speaking of aiosqlite, i need to figure out how to reuse my connection

#

saw something with __aenter__ and __aexit__ but that didn't work (didn't even expect it to)

dull terrace
#

can someone explain the benefit of using async sq version over normal

stone beacon
#

Those are for context managers

dull terrace
#

i've read about async a ton of times and still don't get it entirely

slim ibex
#

so transactions don't block eachother

slim ibex
#

it won't make that much of a difference though

stone beacon
#

Since only one client can be connected to the database at a given time in sqlite aio isn't that much of a boost

slim ibex
#

^

#

if you have two simultaneous connections open, then something is wrong

vivid marsh
dull terrace
pliant gulch
slate swan
vivid marsh
# slim ibex show the whole cog
from http.client import responses 
from typing_extensions import Self
import discord
from discord.ext import commands 

class Utility(commands.Cog):

    def __innit__(self, client):
        self.client = client 
        
    @commands.Cog.listener()
    async def on_ready(self):
         print('Utility is online')

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f'Pong! wow that took {round(client.latency * 1000)}ms')
    
    @commands.command()
    async def purge(self,ctx,amount=1):
         await ctx.channel.purge(limit=amount)
         await ctx.channel.send(f"{amount} messages were deleted", delete_after=5)


def setup(client):
        client.add_cog(Utility(client))```
stone beacon
slate swan
stone beacon
#

oh no no http.client has nothing to do with your discord bot's latency

stone beacon
pliant gulch
slate swan
kindred epoch
stone beacon
#

And your self.client should be an instance of commands.Bot and not discord.Client

#

and ur innit needs to be __ init __

pliant gulch
#

I cba to explain how the connection to the gateway works rn so

vivid marsh
slim ibex
#

and use bot instead of client

vivid marsh
#

I have no clue what was fucked but it’s fixed now thank yall!

slate swan
#

I mean, we all have the same amount of eyes

vivid marsh
slate swan
vivid marsh
#

Gonna be honest I just ended up clicking hot fix until no more lines showed up lmfao

#

And it put me in more shit lol

final iron
dull terrace
#

i found a good way of unpacking tuples lemon_happy

slim ibex
#

ah yes, he knows about *

dull terrace
#

didn't know about namedtuples tho

supple crescent
#

i want to make some basic discord bot ! commands, ik the basics but can seem toi figutre it out, any help would be very appreciated

slim ibex
#

only issue with namedtuple is the syntax for creating it and no types

#

i would use NamedTuple from typing

#

but here you prolly don't want a whole class definition so

#

and tuples are immutable

dull terrace
#

i've had basically zero experience with classes so far, i haven't found a reason i need them yet

slim ibex
#

surprising

#

classes are extremely useful

#

and you shouldn't be jumping into dpy without OOP knowledge

dull terrace
#

🤔 actually maybe it's time to use one

#

i've been passing player data from function to function this whole time

slim ibex
#

uh yeah classes exist

slim ibex
dull terrace
#

i know what all three of those words mean but shared mutable state in combination make zero sense to me

#

but it is 4am, i should probably sleep

slim ibex
#

it can cause one object to stop working correctly

dull terrace
#

so be careful not to overwrite a players variables with another players?

#

oh or

#

i kinda see what you're saying

slim ibex
dull terrace
#

like when you define print and it breaks print

meager chasm
slim ibex
#

like an Animal base class can be the base class for a Snake

#

where the Animal class has a method that resembles the sound the animal makes, and Snake overrides that method to be specific to the snake

meager chasm
#

That's just inheritance though

#

How is it related to shared mutability state

slim ibex
#

that was another topic that came up

#

it isn't related to shared mutable state

meager chasm
slim ibex
#

1 sec

meager chasm
#

Ok ty

slate swan
#

i think he means class instances that are asynchronous

slim ibex
#

?

slate swan
#

class instances that arent in the same state or something like that

meager chasm
slate swan
#

im not sure what youre referring to it seems like maybe youre getting confused with inheritance

slim ibex
#

idk maybe

#

state is a very complicated topic

meager chasm
#

Different instances are supposed to have different states

slate swan
#

yeah

dull terrace
#

is there a quicker way to do this

slim ibex
meager chasm
#

I'm just trying to figure out what shared mutable state is

slate swan
#

so classmethods?

meager chasm
slate swan
#

same

meager chasm
dull terrace
#

dataclass the same but you just define attributes like this?

slim ibex
#

yes

#

you can also use @attr.s

#

same as dataclass just has extra stuff

dull terrace
#

okay neat

slim ibex
#

like making sure a type is something at runtime

slate swan
#

im to lazy to make dataclasses lol

#

Imagine making dataclasses

#

¯\_(ツ)_/¯

dull terrace
#

how is a dataclass more work

slate swan
#

Not a really great way to do that but I'd just use a dictionary

#

And no, it's not more work

#

Dataclasses are better

meager chasm
#

It's more overhead, a dict will be more efficient

dull terrace
#

if i use a dict i will have to pass it back and forth between a lot of functions

#

idk im just gonna do this so i learn how classes work while im doing it, it can be a lil slower

slim ibex
#

dataclasses work exactly like a regular class

slate swan
#

yeah idc im just settiling on using discord.py all these other ones are too weird

dull terrace
#

it worked 🥳

slim ibex
#

PascalCase for classes

sick birch
#

User in your case

slate swan
#

And don't use Sqlite for a discord bot

slim ibex
dull terrace
#

wait wont i have to pass player between functions anyway

sick birch
#

asqlite (preferred, same guy who made discord.py), or aiosqlite

slim ibex
#

aiosqlite pog

slate swan
#

but just to keep it consistent, aiosqlite would be better

sick birch
#

personally i don't like either since i hate writing sql but asqlite seems to be preferred by many

slate swan
#

asqlite ,aiosqlite& Sqlite are all same in terms of syntax and queries, the methods and classes remain almost same too
😶‍🌫️ but yea it's true SQL fails to work conveniently in many cases

slate swan
#

asqlite is not even added to PyPi

#

🙃

sick birch
#

that's just what i'm hearing since it has better defaults

#

which i gotta agree with, row factory is much better than whatever it has normally

#

the weird tuple structure

slate swan
#

Yep

#

pretty easy to learn in my opinion.

#

I mean, just learn some raw SQL and you know it all

#

just learn sql and just play around with the lib

slim ibex
#

i need to know how to reuse my aiosqlite connection, but i'll do that tmmrw

slate swan
#

wdym by reuse?

sick birch
#

the aiosqlite.connect() object i assume

slate swan
#

do you open a connection on each query?

slim ibex
#

i connect to the db in my subclassed bot class, but i don't want to have to open a connection every query

sick birch
#

tie it to your bot var, preferably not in on ready

slate swan
#

just keep the connection open permanently

slim ibex
#

i connect in an overridden start method

slate swan
#

just have a connect method on a connection to the gateway and not on ready

#

so it would be on_connect

slim ibex
#

ahh ok

#

so i wouldn't need start

slate swan
#

a start method? or

slim ibex
#

ye

sick birch
#

the way i do it:

class Bot(...):
  ...
async def main():
  myBot = Bot(...)
  myBot.con = await aiosqlite.connect(...)
  try:
    await myBot.start(...)
  finally:
    await myBot.con.close()
asyncio.run(main())
slate swan
supple crescent
#

can anyone help mw with some bot basics?

slate swan
#
bot = Bot(...

@bot.event
async def on_ready():
     asyncio.run(connect())

async def connect ():
     await bot.wait_until_ready()
     bot.db=# make connection```
#

is what I'd do

sick birch
#

uhm

sick birch
#

I wouldn't do that

slim ibex
#

i had it in overridden connect before

slate swan
dull terrace
#

oh, classes are actually really simple

sick birch
#

asyncio.run() should really be only used as a starting place for your code, so on_ready() can get called multiple times and screw over the event loop

slim ibex
#
async def start(self, token, reconnect) -> None:
  DB_PATH = "./bot/db/bot.db"

  async with aiosqlite.connect(DB_PATH) as self.db:
    BUILD_PATH = "./bot/db/build.sql"

    if os.path.exists(BUILD_PATH):
      with open(BUILD_PATH, "r") as f:
        await self.db.executescript(f.read())

    await self.db.commit()

  await super().start(token, reconnect=reconnect)

i have this rn

slate swan
sick birch
slate swan
# slate swan Explain

on ready can trigger multiple times as it gets triggered on cache population i suggest you use on_connect which only gets triggered once and its when the bot connects to the gateway

sick birch
slate swan
#

on ready can be fired multiple times.

slate swan
sick birch
sick birch
#

that would work alright as well

slim ibex
#

my method?

sick birch
#

given that you use asyncio.run(start(...)) on it

sick birch
slim ibex
#

ah no, I don't

sick birch
#

something similar would work too

#

plenty of ways to go about it

slim ibex
#
from bot import Bot
import logging


def main() -> None:
    logging.basicConfig(level=logging.INFO)

    bot = Bot()
    bot.run()


if __name__ == "__main__":
    main()

this is my entry point file

slate swan
#

Won't self.db close the connection as soon as the context manager is out?

slate swan
sick birch
slate swan
sick birch
#

unfortunate, don't know if we have a one-time only on_ready sort of thing built-in

slim ibex
#

would i, asyncio.run(start(...)) before bot.run()?

sick birch
#

the former is a lower-level approach to bot.run() so only do one or the other

slim ibex
#

ok, so I can just keep it as is

sick birch
slim ibex
#

no, i only have bot.run()

sick birch
#

yeah that works but it's not as flexible imo