#discord-bots

1 messages · Page 817 of 1

cold sonnet
#

if URL == 'None' oh well that doesn't work like that

#

and why is it uppercase, so triggering

vale wing
#

!d discord.BanEntry

unkempt canyonBOT
#

class discord.BanEntry```
A namedtuple which represents a ban returned from [`bans()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.bans "discord.Guild.bans").
terse stream
vale wing
#

@pure tartan nvm found a better thing

cold sonnet
#

just make everything lowercase and use if url is None:

red sundial
#

^

vale wing
#

Fetch a ban using guild.fetch_ban and get its reason

red sundial
#

what fork are you guys using(if you are using one)

cold sonnet
#

disnake

vale wing
unkempt canyonBOT
#

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

Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry") for a user.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
cold sonnet
vale wing
#

Fetch ban entry in your listener and get its reason attribute

cold sonnet
#

what version of python is this

red sundial
terse stream
#

10

slate swan
cold sonnet
#

oh and don't use '', told you

pure tartan
cold sonnet
red sundial
#

@terse stream don't enclose None in ""

slate swan
#

!e "I" is "I"

unkempt canyonBOT
#

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

<string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
red sundial
#

its just None

slate swan
#

that's the error.

red sundial
cold sonnet
#

didn't know that error existed

red sundial
#

same lol

vale wing
#

It is not an error but a warning, I wouldn't call them the same

red sundial
#

so i guess use == instead of is

slate swan
#

It's just a warning tho

cold sonnet
#

I've never made a mistake like that 😎

slate swan
#

Or just use None datatype instead of "None"

red sundial
#

yup

molten silo
#

i like it like this ver

terse stream
red sundial
#

its just emptyness

terse stream
slate swan
#

Off topic but is it possible to make a class which is a subclass of 2 other classes? For reference a class which is a subclass of asyncio.TimeoutError and a custom Exception based class too

red sundial
#

also this is off topic but you might wanna use a formatter like black

terse stream
red sundial
#

no offense but your code is very poorly formatted

red sundial
#

yeah

terse stream
#

😅

red sundial
#

why are you making discord bots

#

do you even know the meaning of async lol

terse stream
slate swan
#

!Pep8 guide gives you the neatest way to write code in py

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

red sundial
slate swan
#

and if needed just use black to format the code

#

and hey sar

red sundial
#

yup black is the best

slate swan
#

hey okiii

#

hyd?

#

decent, just trying to make an Api wrapper

slate swan
terse stream
slate swan
#

sinces there's no async one yet

#

i need to make endpoints for akeno

slate swan
cold sonnet
slate swan
#

the hell

slate swan
#

my client didnt got that msg until i pressed the reply lol

cold sonnet
#

I'm in love

slate swan
#

thats cool

terse stream
terse stream
quick gust
cold sonnet
slate swan
#

I'm keeping it simple ```py
import pokeapi, asyncio

client= pokeapi.Client()
async def main():
pokemon: pokeapi.Pokemon = await client.get_pokemon(name/id)

asyncio.run(main())```

slate swan
cold sonnet
#

not == 'None', not == 'NONE', replace all that with is None

#

@terse stream

quick gust
slate swan
terse stream
cold sonnet
#

send the link again

quick gust
#

Great, you can dm me the repo link whenever you're able!

slate swan
terse stream
slate swan
slate swan
#

a bool, by default set to True

pure tartan
terse stream
slate swan
slate swan
cold sonnet
#

just like this
if URL == 'None' and Title != 'None' and Description != 'None': no
if URL is None and Title is not None and Description is not None:yes

slate swan
#

with a dict

slate swan
#

lolll

#

I use dict too,but in case the file restarts the json is read first

slate swan
#

the data from api stasys same forever so recaching it won't make sense

slate swan
#

or am i confusing it with a backup or a log?

slate swan
slate swan
#

I stated this for a Pokemon bot but now seems kinda fun

slate swan
slate swan
#

me who asks andy a question everyday

#

I'll make the cache kwarg accept a string, if the string is "memory" it will just cache in dictionary, if it's "disk" : memory + json

quick gust
#

I'm probably gonna ask alot of questions too! Newbie in making API wrappers

slate swan
#

my akeno client always caches

#

so it wont strain the api

quick gust
slate swan
#

unlike robin he makes apis and not api wrappers🏃

slate swan
quick gust
#

just a little bit of guidance should be good for me then

slate swan
#

lurking I'm always up for it

slate swan
slate swan
#

yesssir

#

i havent used websockets which seem hard imo but idk

#

since in a websocket you need to make a heartbeat to keep the connection alive

#

the pokeapi is a rest one so needs only gets

#

a gateway connection is not required

#

those are http request methods so it really doesnt matter

#

event

cold sonnet
#

ey

slate swan
#

not event()

rough wadi
#

You do event

cold sonnet
#

we all are bad

rough wadi
#

No ()

cold sonnet
#

if URL == 'None' and Title != 'None' and Description != 'None':

#

this is almost legitimate code

#
@bot.event
async def on_command_error(ctx,error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.send('Please provide all the arguments **Type NONE if you dont want to use something**!!')
```cause of this
slate swan
#

just comparing strings and not NoneType

cold sonnet
#

Type NONE if you dont want to use something

slate swan
#

no its None

#

your jokes are bad

cold sonnet
#

it's not a joke

#

it's made so that you can put a not-required argument that's after a not-required argument

quaint epoch
#

how do i change the perms of a member in the guild? like give them admin or smth?

quaint epoch
slate swan
cold sonnet
#

you're being a poopoo

slate swan
#
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\testing\modules\config.py", line 92, in on_command_error
    await self.error_channel.send(self.error_embed)
TypeError: can't send non-None value to a just-started coroutine
slate swan
slate swan
velvet tinsel
quaint epoch
velvet tinsel
#

+10 xp

#

levelled up

cold sonnet
#

for just ten....?

quaint epoch
#

+5k secret xp

#

GG @slate swan , gr8 job on keeping the server alive 👍

#

(took that from MEE6)

cold sonnet
#

that's bs

quaint epoch
cold sonnet
#

why not steal things from your own bot

slate swan
#

why so many pings

quaint epoch
cold sonnet
#

three

#

four

slate swan
#

jeez

quaint epoch
#

@slate swan do you want a fourth ping?

slate swan
#

5pings

velvet tinsel
slate swan
#

but its other error ..

slow fog
slate swan
#

i swear if i keep getting pinged

pallid mango
#

does anyone know of a way to unban a user through the console?

slate swan
unkempt canyonBOT
#

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

Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
full lily
#

the bot console?

pallid mango
#

yes

#

yes

full lily
#

you can't really interact with the api through the terminal with d.py

slate swan
#

i mean you can use input but that isnt async

pallid mango
#

do you know of a way to unban someone like every 30 seconds or something

#

like a certain person

full lily
#

task?

#

discord.ext.task

slow fog
full lily
slate swan
#

why unban someone every 30 seconds?

pallid mango
#

well basically

slate swan
slate swan
quaint epoch
pallid mango
#

i made a server for someone and then they turned, but they are refusing to kick my bot, so i want to get rid of my bot. but then they banned me

slow fog
full lily
slate swan
quaint epoch
pallid mango
#

so i wanna unban myself using my bot.

slate swan
quaint epoch
pallid mango
#

admin

quaint epoch
pallid mango
#

no?

#

its my bot...

quaint epoch
pallid mango
#

its my bot.. lmfao

quaint epoch
#

just remove your bot then

slate swan
#

unban yourself with your own bot thats kinda abusing power dont you think?

quaint epoch
#

!rule 8

unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

quaint epoch
#

whoops

slate swan
#
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<Config.get_channel() done, defined at c:\Users\PC\Desktop\testing\modules\config.py:24> exception=AttributeError("'_MissingSentinel' object has no attribute 'request'")>
Traceback (most recent call last):
  File "c:\Users\PC\Desktop\testing\modules\config.py", line 25, in get_channel
    self.error_channel = await self._bot.fetch_channel(ERROR_CHANNEL)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 1575, in fetch_channel
    data = await self.http.get_channel(channel_id)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\http.py", line 275, in request
    async with self.__session.request(method, url, **kwargs) as response:
AttributeError: '_MissingSentinel' object has no attribute 'request'
Ready
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\testing\modules\config.py", line 94, in on_command_error
    await self.error_channel.send(embed=self.error_embed)
AttributeError: 'Config' object has no attribute 'error_channel'
quaint epoch
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

pallid mango
#

hows it breaching TOS though?

quaint epoch
#

Your using your bot to gain access to a server which the owner didn't want you in, just remove your bot from there

pallid mango
#

how.

#

thats literally all im trying to do but idk how

slate swan
#

youre avoiding a ban which was set to you which youre trying to go over with your bot its probably not against tos but it seems wrong tbh you were ban for a reason no?

pallid mango
#

no

#

hold on

slate swan
#

then why are you trying to unban yourself every 30 seconds?

#

seems like they dont want you in there server if you get banned everytime?

pallid mango
#

i literally made the server for the guy, passed ownership, and found out he's weird so i asked him to remove my bot when i left and he didnt

slate swan
#

not that

#

!d discord.Guild.leave

unkempt canyonBOT
#

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

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
slate swan
#

here make your bot leave

final iron
quaint epoch
#

make your bot non-public

pallid mango
final iron
#

How does that not break tos

quaint epoch
#

then he can't add it

pallid mango
#

dude its already in there

slate swan
pallid mango
#

okay

slate swan
#

if you cant find the id loop through all the ids that the bot can see

pallid mango
#

bruh how i get the guild id if i cant join the server

slate swan
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
pallid mango
#

oh

slate swan
#

check the name and id lol

pallid mango
#

hmm

#

can u just get the guild id for me lol, i have inv link

final iron
#

Just look for yourself?

slate swan
#

no sorry

pallid mango
#

bruh

slate swan
#

sounds like a you problem

pallid mango
#

i cant get it because it says user is banned?

final iron
#

Seems like you're actually just trying to get revenge

slate swan
pallid mango
final iron
#

Look through your list

quaint epoch
#

just make your bot unpublic

final iron
#

Find the id

quaint epoch
#

then remove it from the server

final iron
#

Then leave the guild lmao

#

It's not that hard

pallid mango
#

where do i find the guild id holy balls

#

like what list

quaint epoch
slate swan
#

your question has been answered why continue?

final iron
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
slate swan
quaint epoch
#

it's a list of guilds

pallid mango
slate swan
quaint epoch
slate swan
pallid mango
#

okay thats cool but where would i put the code?

quaint epoch
slate swan
#

most people dont say im weird but alr

quaint epoch
#

this gives me bad vibes, not directly help you

slate swan
#

same

final iron
pallid mango
slate swan
#

gtg later guys

pallid mango
quaint epoch
quaint epoch
pallid mango
#

true

final iron
#

And have the code to leave inside of it

#

You're giving me very bad vibes. This is such easy code

pallid mango
final iron
#

Bro what

#

Literally a command

pallid mango
#

WHAT TYPE

final iron
#

Prefix command

pallid mango
#

okay

final iron
#

Wut

#

It isn't this complicated

pallid mango
#

and how would i send the command if im banned

quaint epoch
pallid mango
#

okay

final iron
pallid mango
#

okay i did it

#

thank you

quaint epoch
#

your bot left the server?

pallid mango
#

yes

quaint epoch
#

alr

pallid mango
#

thank you guys, i just didnt want him using my work

final iron
#

Okay?

quaint epoch
pallid mango
#

true

slate swan
#
@bot.listen
async def on_message(message):
    channel_suggestion_id = 941430665256251432
    channel = bot.get_channel(channel_suggestion_id)

    if message in  channel:
        embed = discord.Embed(colour=discord.Colour.red())
        embed.set_author(name=f"Suggestion by {message.author}", icon_url=f'{message.author.avatar_url}')
        embed.set_thumbnail(url='{}'.format(member.avatar_url))
        embed.add_field(name=f"{message.content}", value='\n\u200b', inline=False)
        await message.channel.send(embed=embed)```
#

Wait nvm

#

😭 i didnt see "await"

slate swan
#

why it isn't working?

slate swan
#
  File "C:\Users\30694\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\30694\Desktop\All\Gif Server Bot\main.py", line 315, in on_message
    if message in  channel:
TypeError: argument of type 'TextChannel' is not iterable```
slate swan
slate swan
serene mantle
#

Hey guys, im developing a cog that is supposed to send a number to a user in DM's, and the user is supposed to repeat this number. Im using Discord.py.

#

anyone know how to get response from a user?

manic wing
#

!d discord.Client.wait_for

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**...
manic wing
#

you just check if the user is the user and the channel isinstance discord.DMChannel

slate swan
#

!d discord.DMChannel

unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
desert badger
#

can anyone help me rq

#

i just wanna confirm something

#
# Channels

welcome_channel = client.get_channel(839070995745603585)

will this work ?

#

so i can always do like

@client.command()
async def idk(ctx):
  await welcome.channel.send("test")
#

wait

#

ill just try it myself im so smart why am i asking

manic wing
desert badger
manic wing
#

jolly good question

velvet tinsel
#

...

slate swan
#
except:
  #do something```
tall arch
#

guys, how do i get my vs code file to debug as it keeps sending this message.

slate swan
velvet tinsel
#

.....

#
try:
  ...
except <exception name>:
  ...
#

bare exceptions are bad, so I won't recommend it

#

well done

slate swan
#

ganggang yessir

#

Is there a way to check if a user's dms are off without using a try & except method. I'd like to be able to check without having to send a test message to the user.

velvet tinsel
velvet tinsel
#

try except is the only thing I can think of

final iron
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
velvet tinsel
slate swan
#
@client.command()
async def serverinfo(ctx):
    """Displaying server info"""
    embed=discord.Embed(title="Server Information")
    embed.add_field(name="Server Name", value=ctx.message.guild.name, inline=True)
    embed.add_field(name="roles:", value=(ctx.message.guild.roles), inline=True)
    embed.add_field(name="Members:", value=len(ctx.message.guild.members))
    embed.add_field(name="Channels:", value=len(ctx.message.guild.channels))
    embed.add_field(name="Members:", value=str(ctx.message.author.mention))
    embed.set_footer(text="Check out discord. gg/shops for cheap and affordable Discord bots and other services")
    await ctx.send(embed=embed)```

```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.1.value: Must be 1024 or fewer in length.
#

What's wrong here

slate swan
#

Reduce the text

#

Well, from where specifically

#
embed.add_field(name="roles:", value=(ctx.message.guild.roles), inline=True)
                                      ^^^
#

ah

#

guild.roles are exceeding 1024 char length

#

How do I state the number of roles?

slate swan
#

Umm I think len(...roles) ?

#

okay thanks

#

wait

slate swan
serene mantle
#

If a user sends my bot a message, how can i read this message?

#

is there some sort of on event?

#

or how does that work

slate swan
#

You mean dm messages?

serene mantle
#

yes

slate swan
#

Bot receives it with same event MESSAGE just like other messages

serene mantle
#

really

slate swan
#

check if message.guild is None in on_message

serene mantle
#

1 sec

serene mantle
#

like this?

slate swan
#

Not like comparing string

#

check if message.guild is NoneType

dusk dust
#

my bot is sending the message a lot of times... can any1 help me?

@client.event
async def on_message(message):

    if 'Nota'.lower() and 'Razão'.lower() and 'Staff'.lower() and 'Nick'.lower() and ':' not in message.content and message.channel.id == 941458805676462090:
        await message.author.send('**EI**! O canal [#941458805676462090](/guild/267624335836053506/channel/941458805676462090/) não foi feito para bagunça! Utilize ele da maneira **CORRETA**, por gentileza.')
        await message.delete()
    else:
        mensagem = message.content
        channel = client.get_channel(941458805676462090)
        await channel.send('**NOVA AVALIAÇÃO RECEBIDA**\nEsta avaliação foi feita pelo {0}:\n\n{1}'.format(message.author.mention,mensagem))
        pass
serene mantle
slate swan
serene mantle
serene mantle
hot cobalt
#

'Nota'.lower() and 'Razão'.lower() and 'Staff'.lower() and 'Nick'.lower() and ':' not in message.content this is almost certainly not doing what you think @dusk dust

slate swan
serene mantle
#

ohh

#

if message.guild is "None":

dusk dust
serene mantle
#

np

dusk dust
#

i am going to test

slate swan
hot cobalt
slate swan
#

Add a check to see if messages sender is not the bot

hot cobalt
#

Or "staff" etc

serene mantle
hot cobalt
#

Because it's not checking that

#

At the very least, you have a lot of redundant things in that if-statement that do effectively nothing

serene mantle
#

@slate swan if message.guild is "None": this right?

hot cobalt
#

if 'Nota'.lower() and 'Razão'.lower() and 'Staff'.lower() and 'Nick'.lower() and ':' not in message.content and message.channel.id == 941458805676462090: is functionally the same as if ':' not in message.content and message.channel.id == 941458805676462090:

slate swan
#

None is a string and not the NoneType

dusk dust
slate swan
#

its fine here?

serene mantle
#

xD

#

i dont wanan wait there so if message.guild is NoneType:

slate swan
#

no

serene mantle
#

omg

slate swan
#

is None

serene mantle
#

whats i did

dusk dust
# dusk dust
  • when i type something different of:
    "Nick: jsadasd
    Staff: asjdjsd
    Nota: asdasd
    Razão: asdsad"
slate swan
serene mantle
#

if message.guild is None:

slate swan
#

yes

#

Yes

serene mantle
#

tysm

slate swan
#

what's wrong here?

@commands.command(aliases=['photo', 'img', 'icon', 'av'])
    async def avatar(self, member: discord.Member = 'none'):
      if member != 'none':
        aembed = discord.Embed(title=f"{member.display_name}'s avatar")
        aembed.set_image(url=member.avatar_url)
        aembed.timestamp = datetime.datetime.utcnow()
        await self.send(embed=aembed)
      else:
        aembed = discord.Embed(title='Your avatar')
        aembed.set_image(url=self.author.avatar_url)
        aembed.timestamp = datetime.datetime.utcnow()
        await self.send(embed=aembed)```
hot cobalt
#

At the very least, there's a lot of redundant stuff here

slate swan
#

why is everyone making None a string today?????

serene mantle
#

lmao

#

🤣

dusk dust
hot cobalt
slate swan
#

Have python like released some changes to None or what, I've been out for so long

#

None is a Nonetype and not a string

final iron
slate swan
slate swan
dusk dust
#

no?

slate swan
slate swan
hot cobalt
slate swan
#

so how can i fix that?

hot cobalt
slate swan
hot cobalt
#

I'm also not too sure what the .lower() is there for

slate swan
#

oof...how?😁

hot cobalt
#

It's sort of pointless if you're just calling it on a string literal

#

Just change the literal instead

slate swan
#

now i have member: discord.Member

balmy ivy
#

why does this show as a error?

dusk dust
slate swan
#

@bot.command and async def must be the one under the other

#

and your indents arent correct

hot cobalt
slate swan
# slate swan oof...how?😁

Your "member" parameter is assigned to .Context and your .Member doesn't exists. Your function receives a value like (context, member, ...) but you took it like (member, ...) hence declaring .Context to your "member". To fix, just accept a ctx before member

#

it should be 4 spaces or a tab for each level of indentation

hot cobalt
#

The if-statement will be True

slate swan
#

oh ok

slate swan
#

lemme try

slate swan
hot cobalt
#

Anyway, as to why it's sending multiple messages

#

It's just responding to it's own messages

#

So you'd probably want to just throw a ```py
if message.author == client.user:
return

#

Up the top of your on_message so that it ignores itself

slate swan
slate swan
#

not authot

#

f

#

you should read your errors

#

sorry

#

it will help you

#

wait, i wrote it wrong here. It is author

#

you did self.author

#

its ctx.author your class has no attr with author

#

ah yes

#

ctx does have a author attr do

final iron
#

What's the context class in the docs?

#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
slate swan
#

lol

slate swan
slate swan
#

: )

#

❤️

#

btw check how satisfying is my pfp

slate swan
slate swan
slate swan
balmy ivy
#

how to i restart my discord bot? like turn off and back on?

slate swan
#

what for?

balmy ivy
slate swan
#

for new commands?

balmy ivy
#

yea

slate swan
#

you can use cogs and reload it so the bot stays on and gets new commands

#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
balmy ivy
#

whats that?

slate swan
#

the reload your cogs

balmy ivy
#

ok do i paste it in ?

slate swan
#

first do you have cogs?

balmy ivy
#

nah

slate swan
hoary cargo
#

artistic_hmm man, discord fucked up again

slate swan
#

hi! it's me again

i have this:

@bot.command()
async def server(ctx):
    embed = discord.Embed(title = f"{ctx.guild.name} Info", description = "Information of this Server", color = discord.Colour.blue())
    embed.add_field(name = '🆔Server ID', value = f"{ctx.guild.id}", inline = True)
    embed.add_field(name = '📆Created On', value = ctx.guild.created_at.strftime("%b %d %Y"), inline = True)
    embed.add_field(name = '👑Owner', value = f"{ctx.guild.owner}", inline = True)
    embed.add_field(name = '👥Members', value = f'{ctx.guild.member_count} Members', inline = True)
    embed.add_field(name = '💬Channels', value = f'{ctx.guild.text_channel_count} Text | {ctx.guild.voice_channel_count} Voice', inline = True)
    embed.add_field(name = '🌎Region', value = f'{ctx.guild.region}', inline = True)
    embed.set_thumbnail(url = ctx.guild.icon_url)
    await ctx.send(embed=embed)```
and the error is `'Guild' object has no attribute 'text_channel_count'`
final iron
#

Have you read the error?

#

Why are you using random attributes and expecting they will work?

final iron
#

!d discord.Guild.text_channels

unkempt canyonBOT
#

property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.
final iron
#

Returns a list

#

Use len() on it to get the amount of text channels

slate swan
#

um, i didn't understand

#

oh ok

#

where i write len()?

slate swan
unkempt canyonBOT
#

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

4
final iron
#

You use len() on a list to get how many elements it has

slate swan
#

len gets the length of how much elements something has

slate swan
#

ok

#

i wasn't supposed to paste this in the code

#

no

#

it was an example to show you how len works

#

ok

#

len({ctx.guild.text_channel_count}) like this?

final iron
#

Spoon feeding is so tempting

slate swan
slate swan
#

nice

final iron
#

I showed you above what to do. Do you not understand something?

slate swan
#

so and so

#
len(ctx.guild.text_channels)
#

aaaaaaaaaaaaaaaaaaaa

final iron
slate swan
#

discord.interactions isnt a module

slate swan
worldly oyster
#
Traceback (most recent call last):
  File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.devcog' raised an error: ModuleNotFoundError: No module named 'discord.interactions
#

thats the error we are getting

slate swan
#

im getting so much pings

worldly oyster
#

sorry

slate swan
#

sorry

#

guys discord.interactions isnt a module

worldly oyster
#

then what do we do to fix it?

slate swan
#

see

#

and why not use disnake for interactions

#

dpy doesnt have slash commands

worldly oyster
#

im confused on this

slate swan
#

confused on what

worldly oyster
#
Traceback (most recent call last):
  File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.devcog' raised an error: ModuleNotFoundError: No module named 'discord.interactions
#

this is what is poping up

slate swan
#

oh my god

final iron
#

Then don't import it...?

slate swan
#

DISCORD.INTERACTIONS ISNT A MODULE

#

!pypi discord.interactions

unkempt canyonBOT
worldly oyster
#

then what is the error?

slate swan
#

really why use this lib

#

its getting called

#

idk its your code im not a fortune teller?

#

you want me to grab the solution from your mind?

worldly oyster
#

yes

#

i do want you do

#

to*

slate swan
#

im having a headache already tbh

worldly oyster
#

im actuall0y confused about this tho it js dont make sense

slate swan
#

it does

hoary cargo
slate swan
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'nothing'
slate swan
#

omg would you look at that

#

a ModuleNotFoundError

#

guys its basic python

hoary cargo
slate swan
#

then what is the error

worldly oyster
#

import discord
from discord.ext import commands
import keep_alive
import json
from asyncio import sleep
import colorama

#

only imports

slate swan
#

ModuleNotFoundError

#

not importing it how

hoary cargo
#

guys what does it mean i can't read 😢

slate swan
#

👁️👁️

worldly oyster
#

import discord
from discord import commands

only imports in cog

slate swan
#

bro

#

ModuleNotFoundError
only raises when trying to import a module

#

python just wont break for no reason

#

if your getting errors its most likely an error with your code and not internals

#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.devcog' raised an error: ModuleNotFoundError: No module named 'discord.interactions

👁️👁️

#

are you blind bro

hardy wing
#
if health2 <=0.0:```
would any of you happen to know why this'd return true if health2 is 40.0 cause it is for me
hardy wing
#

for a discord bot so figured it'd be more appropriate to ask here but ok

slate swan
#

that snippet isnt really related to it your saying why an if statement returns True

#

python general is more appropriate imo

unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

False
sick birch
#

don't know about that

slate swan
#

hi robin hyd?

gusty hatch
#
  @commands.command()
  async def uptime(self, ctx):
      now = datetime.datetime.utcnow()  # Timestamp of when uptime function is run
      delta = now - start_time
      hours, remainder = divmod(int(delta.total_seconds()), 3600)
      minutes, seconds = divmod(remainder, 60)
      days, hours = divmod(hours, 24)
      if days:
          time_format = "**{d}d {h}h {m}m and {s}s**"
      else:
          time_format = "**{h}h {m}m and {s}s**"
      uptime_stamp = time_format.format(d=days, h=hours, m=minutes, s=seconds)
      em = discord.Embed(description=f"{self.bot.user.name} has been running for: {uptime_stamp}")
      await ctx.send(embed=em)

Whats wrong with my uptime command? I made it back in august , Quit discord came back last month, most of my cmds dont work anymore so im fixing them , but this one sends no error at all

bold surge
#

is start time defined?

hardy wing
#

on replit is it possible to make a database specific to a user or server

slate swan
hardy wing
#

yeah thought that was a solution just making sure there isn't already like a separate thing for it

slate swan
#

nah not really just make the tables in same db

#

replit's db is slow, just use sqlite or something

sick birch
#

replit db? yikes

slate swan
#

yeah its bad slow

slate swan
unkempt canyonBOT
slate swan
#

they have it integrated for projects

sick birch
#

i know what it is, just it's pretty bad

slate swan
#

yeah its very slow

#

and ill assume it uses json like structure

#

yeah i think it does

sick birch
#

ouch

slate swan
#

like mongo but horrible

sick birch
#

you know i never got the appeal of replit or any of their "tools"

pliant gulch
#

5mb per value lmao

#

EdgeDB looking real nice

slate swan
#

andy, how do i get the Client's latency in rin?

slate swan
#

oh ok

#

i tried client.gateway.heartbeat but it returns a dict

#

or is it not available yet?

pliant gulch
#

I haven't added the latency, I can do that rq by taking times from last ACK'd heartbeat

slate swan
#

whats a ACK hb

pliant gulch
#

Acknowledge

slate swan
#

ah ic

slate swan
#

docs is the part that sucks while development

pliant gulch
slate swan
#

bro.

pliant gulch
#

Only the frontend methods are documented in this file though

slate swan
#

yea thats what im doing

#

andy really said yeah learn my way

pliant gulch
#

Any particular question then?

slate swan
#

😭

pliant gulch
#

Cause I can probably answer

slate swan
#

ah, line 352-422 has all the events listed

pliant gulch
#

It was a pain writing them out

#

I made the events that way to make it easy to overload wait

final iron
pliant gulch
#

Has the newer events that discord.py doesn't have due to it being archived, idk about the forks though they probably have 100% support

#

The wrapper doesn't even parse all the events yet, just allows for them to be dispatched at the very least

#

I still need to add those sadly 😔

final iron
#

I mean development seems to be progressing fast

slate swan
#

but andys wrapper has collectors those are coolpithink

pliant gulch
#

not really progressing fast 😔

slate swan
unkempt canyonBOT
#

rin/gateway/handler.py lines 124 to 130

if code == OPCode.HEARTBEAT_ACK:
    if self.last_heartbeat is not None:
        self.latency = (
            datetime.now() - self.last_heartbeat
        ).total_seconds()

    _log.debug("GATEWAY ACK'D HEARTBEAT.")```
pliant gulch
#

Welp I did my one commit for the week, time to go back to being lazy

slate swan
#

nice commit

slim ibex
#

Rin!

#

Best lib

pliant gulch
#

The parser code for gateway is so disgusting

#

Someone help me refactor, perhaps in a more decentralised way

#

😔

final iron
#

Yeah bro I got you

pliant gulch
#

I feel like I should do model specific parsers, splitting up parsers into the spots where certain models use them

#

But it would be harder to do stuff

slate swan
#

why so?

pliant gulch
#

The parsers are easier to use in the same file cause they can be interconnected

slate swan
#

parses are for strings i suppose right?

pliant gulch
#

Parsers are for the dispatch data received from the gateway

slate swan
#

to parse the data?

pliant gulch
#

It turns the raw dict, e.g message dict into a message object for you to use

slate swan
#

yeah it parses the data

final iron
#

We are also implementing objects for our Twitter lib

slate swan
#

i hate myself for listening to watergazes

pliant gulch
#

Perhaps I will do a parser refactor before I do commands

slate swan
final iron
pliant gulch
#

Cause this is something I've been wanting for a while

final iron
#

You agreed

slate swan
pliant gulch
#

Perhaps something procedural in design

final iron
#

💀

slate swan
maiden fable
#

Best way to automatically parse the events to their own classes, like on message in message class would be to do something like

event_type = "Message"
parsed = eval(f"{event_type}({json})") 

Provided Message is a class name 🤣

slate swan
unkempt canyonBOT
#

rin/gateway/handler.py lines 139 to 145

parser = getattr(self.parser, f"parse_{event.name.lower()}", None)
self.client.dispatch(Events.WILDCARD, event, data["d"])

if parser is not None:
    return self.loop.create_task(parser(data["d"]))

return self.loop.create_task(self.parser.no_parse(event, data["d"]))```
pliant gulch
#

But in a safer way, without eval

maiden fable
#

Damn. So u ain't using multiple if statements to check the event type lmao

slate swan
pliant gulch
#

that would be pretty idiotic

maiden fable
#

Ikr

#

But i did it once

pliant gulch
#

iirc discord has like around 50 dispatchable events

#

👁️ 👁️

maiden fable
#

Yea there are many

slate swan
#

jeez

maiden fable
#

Oki

slate swan
#

thats allot of events

maiden fable
#

Start writing if statements for all of them

#

Thanks

pliant gulch
#

Hunter contribute and help me decentralise or make the parsers procedural

#

You've made a wrapper before so it should be light work

maiden fable
#

Uhhh, I myself haven't coded since a month or two now idk

slate swan
#

your smart words always give me strokes

maiden fable
#

Whose

pliant gulch
#

Actually there is no way for me to make this procedural

maiden fable
#

What do u even wanna do

pliant gulch
#

I will have to manually add each one, or at the very least make a good system for adding them

#

I want a sort of generic builder

#

But for parsers, but that's not trivial

slate swan
#

bot.wait_for reaction pls help
looked at manuals

#

python btw

maiden fable
maiden fable
slate swan
#

not rlly

pliant gulch
# maiden fable Generic builder?

Like imagine how my event class currently works. It works with any future event and all the current events with only the event name

#

I don't need to make any more classes, functions, etc

slate swan
pliant gulch
#

But that won't be easy to do/possible for the parsers

#

as they do different things

placid grove
#

How i use Custom Status?

slate swan
#

for bots you cant

placid grove
#

Yes for bots

slate swan
#

nope you cant

placid grove
#

oh

slate swan
#

bots dont have access to custom statuses

placid grove
#

Ohk

final iron
pliant gulch
slate swan
pliant gulch
#

I don't think I'll let nova do a core PR 😔

maiden fable
#

😂

slate swan
#

😭

maiden fable
#

Blanket?

pliant gulch
#

Blanket is working on his web framework

maiden fable
#

is it just me or everyone is working on something except me

maiden fable
#

Sad

slate swan
#

lol

hoary cargo
maiden fable
slate swan
#

bro

hoary cargo
#

Bad

#

Leave WarBlank

pliant gulch
#

OOHHH

maiden fable
#

?

pliant gulch
#

I can make the parsers generic, ig then pass Event("Blah") to it perhaps

maiden fable
pliant gulch
#

And then it would register that parser to automatically listen for the event

slate swan
pliant gulch
#

But this would mean I need to make them classes

#

A generic method wouldn't really work well

slate swan
#

yeah

#

and it would have better handling no?

maiden fable
#

Wait wait wait... My idea of a simple parser would be...

json = await response.json() 
event_type = json["event"]
parsed = eval(f"{event_type.capitalize()}({json})") 
await bot.dispatch(...) 
slate swan
#

i mean that doesnt look bad ig

maiden fable
#

Idk if that's what Andy is doing

#

Haven't read the source code

pliant gulch
#

that's close to what I'm doing

#

But still the issue persists

pliant gulch
#

I need to do a lot of things inside of the parser manually

#

So at the very least I want to make it easier to scale

maiden fable
slate swan
pliant gulch
maiden fable
#

Ah, the extra processing to look in the cache too?

slate swan
#

the heck is this deco for

@attr.s(slots=True)

and what does this operator do :=

visual island
#

what does this operator do :=
assigning in cool way (if statements)

slate swan
#

bro

pliant gulch
#

Decorator is to make a dataclass with slots

slate swan
#

🏃

pliant gulch
#

There is really no reason for me to slot though

#

The only attribute is client

maiden fable
#

Walrus

#
if role := discord.utils.get(...) == None:
    print(role) 
else:
    print(role) 

Vague example, done cry about it

visual island
balmy ivy
slate swan
slate swan
slate swan
final iron
tiny ibex
#

Can someone tell how to check if a message has an attachment?

slate swan
#

!d discord.Message.attachments

unkempt canyonBOT
tiny ibex
#
if message.attachments:
     print("Message has an attachment!")
if not message.attachments:```
final iron
tiny ibex
#

Doesn't work

slate swan
tiny ibex
maiden fable
#

It assigns and compares the variable in one place

maiden fable
slate swan
maiden fable
#

Idk

slate swan
#

🏃

maiden fable
#

What's message?

final iron
maiden fable
#

Most probably the message doesn't has any attachment

slate swan
#

lmaooo

tiny ibex
tiny ibex
maiden fable
#

😐

#

Ok I'm out. Oki, he's yours

tiny ibex
slate swan
tiny ibex
#

NVM ig I forgot to add return 😅

slate swan
#

message.attachment returns a list of attachments (which includes all types of files) in the Message
not message.attachments would be True if the message has no attachments

slate swan
tiny ibex
#
@bot.command()
async def recognize(ctx, url = None):
    if url is None:
        if ctx.message.attachments:
            attachment = ctx.message.attachments[0]
            url = attachment.url
        else:
            em = discord.Embed(title = "No attachement or URL!", description="Hey man you gotta send a file or a URL to recognize the music from -_-", color = bot_embed_color)
            await ctx.send(embed=em)
            return
    query_url = f"https://some-cool-api.herokuapp.com/recognize_music?url={url}"
    async with aiohttp.ClientSession() as session:
        async with session.get(query_url) as resp:
            res = await resp.json(content_type=None)
    title = res['track']['title']
    background = res['track']['images']['background']
    coverart = res['track']['images']['coverart']
    url = res['track']['share']['href']
    subtitle = res['track']['subtitle']
    em = disnake.Embed(title = title, url=url, description=f"by **{subtitle}**", color = bot_embed_color)
    em.set_image(url=coverart)
    await ctx.reply(embed=em)```
slate swan
#
if a := 1 > 0:
    print(a)``` is equivalent to ```py
if a := (1 > 0):
    print(a)``` iirc
#

so, its a:= True

slate swan
#

right thanks

small igloo
#
async def callback(self, interaction: discord.Interaction):
        global item
        id = interaction.user.id
        coin = database.check_coin(id)
        s = int(price[item])*int(self.values[0])
        if coin >= s:
            await interaction.response.send_message(
                f'{interaction.user.mention}, You bought {self.values[0]} {item}! thanks for shopping with us!')
            database.add_item(id, self.values[0], item)
            database.decrease_coin(interaction.user.id, s)
            if self.values[0] == 5:
                if item == "seed":
                    if random.randint(2, 2) == 2:
                        database.add_item(id, 1, "super seed")
                        await interaction.response.send_message(f"wow, {interaction.user.mention} is getting a :superseed: super seed!")
        else:
            await interaction.response.send_message("not enof money E")

i want that code work like this:

i buy 5 seeds
pick random
if it's 2, it will gimme super seed and send message

how

slate swan
slate swan
#

and what's self there? a view class?

final iron
#

Why not just make an attribute?

small igloo
small igloo
small igloo
final iron
small igloo
final iron
#

!e

class TestClass:
    def __init__(self):
        self.attribute = None
    def method(self):
        self.attribute = "hi"
        print(self.attribute)


TestClass().method()
unkempt canyonBOT
#

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

hi
final iron
#

Probably terrible example

slate swan
#

you could have just TestClass().attribute to get the value :p

#

but that would return None

#

yeah since thats the original value

small igloo
# final iron !e ```py class TestClass: def __init__(self): self.attribute = None ...

ok, i not understand, but here's my code

class amount_(discord.ui.Select):
    def __init__(self):
            options = [
                discord.SelectOption(label='1', description='1 item',
                                             emoji=':1_:'),
                discord.SelectOption(label='2', description='2 items',
                                             emoji=':2_:'),
                discord.SelectOption(label='3', description='3 items',
                                             emoji=':3_:'),
                discord.SelectOption(label='4', description='4 items',
                                             emoji=':4_:'),
                discord.SelectOption(label='5', description='5 items',
                                             emoji=':5_:')
            ]
            super().__init__(placeholder='how much', min_values=1, max_values=1, options=options)
    async def callback(self, interaction: discord.Interaction):
        global item
        id = interaction.user.id
        coin = database.check_coin(id)
        s = int(price[item])*int(self.values[0])
        if coin >= s:
            await interaction.response.send_message(
                f'{interaction.user.mention}, You bought {self.values[0]} {item}! thanks for shopping with us!')
            database.add_item(id, self.values[0], item)
            database.decrease_coin(interaction.user.id, s)
            if self.values[0] == 5:
                if item == "seed":
                    if random.randint(2, 2) == 2:
                        database.add_item(id, 1, "super seed")
                        await interaction.response.send_message(f"wow, {interaction.user.mention} is getting a :superseed: super seed!")
        else:
            await interaction.response.send_message("not enof money E")
slate swan
#

and in the method it gets re assigned

small igloo
slate swan
#

eeee you told it was View class

#

but its a Select

slate swan
small igloo
slate swan
#

i asked what's self there, and its a Select

slate swan
final iron
small igloo
small igloo
slate swan
#

you wont follow pep8

#

anyways, where does the variable item come from, and i dont see you using it anywhere other than database.add_item(id, self.values[0], item)

final iron
slate swan
#

functions should be snake_casing and variables, classes should be PascalCase and camelCase is for nothing lol

small igloo
# slate swan anyways, where does the variable `item` come from, and i dont see you using it a...
class shop(discord.ui.Select):
    def __init__(self):
        options = [
            discord.SelectOption(label='brew stand', description='A brewer tool', emoji=':brew:'),
            discord.SelectOption(label='bottle', description='to store water', emoji=':woterbottle:'),
            discord.SelectOption(label='seed', description='farming is really need this!', emoji=':seed:'),
            discord.SelectOption(label='crafting table', description='u need this to do some things', emoji=':crafttable:')
        ]
        super().__init__(placeholder='Shop items', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        h = discord.Embed(title="how much?", description="", color=interaction.user.color)
        view = amount()
        if self.values[0] == "seed":
            global item
            await interaction.response.send_message(embed=h, view=view)
            item = self.values[0]
        else:
            id = interaction.user.id
            coin = database.check_coin(id)
            s = int(price[self.values[0]])
            if coin >= s:
                await interaction.response.send_message(f'{interaction.user.mention}, You bought a {self.values[0]}! thanks for shopping with us!')
                database.add_item(id, 1, self.values[0])
                database.decrease_coin(interaction.user.id, s)
            else:
                await interaction.response.send_message("not enof money E")
slate swan
#

!d discord.ui.Select.values

unkempt canyonBOT
small igloo
slate swan
#

hm

final iron
final iron
small igloo
slate swan
#

!pep8

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

slate swan
#

pycharm will scream at you

final iron
small igloo
#

:v ok

slate swan
#

and it makes it more readable to everyone hence pep8s existence

#

more readable code-> easier for other ppl to understand

#

general style all python devs should follow

small igloo
#

:vvv ok

#

ok, from discord.py server, they said that i need to interaction.followup.send

i try but dont work

slate swan
#

does it not respond at all?

final iron
#

All I want for christmas is for people to follow pep8

#

🙏

slate swan
small igloo
final iron
tender estuary
final iron
#

So many PEP8 rules being broken

slate swan
#

lolll

shadow wraith
#

mf esoteric python is like boiling the egg without the egg 💀

slate swan
small igloo
shadow wraith
#

esoteric python isn't just about unstylish code

slate swan
shadow wraith
small igloo
slate swan
#

its accessed with Client.cache ,any thoughts?

#

should i combine the class in Client itself ?

#

nah

#

iterate thru Guild.roles and use Role.permissions to check if the role has the permission you need

slate swan
#

and why is client in the init?

#

in akeno i just accessed the methods of the cache class

slate swan
final iron
#

yoink

final iron
slate swan
#

how bro

#

gotta remove the preview embed🏃

shrewd inlet
#

Anyone know what I did wrong?

slate swan
shrewd inlet
slate swan
#

attrs

slate swan
# slate swan and why is client in the init?

i need to acess some attributes of Client inside the cacheimpl , remember we talked about the option of caching in memory and disk right? Client.cache_type is required in the CacheImpl to acess its value

#

!d discord.Guild.roles

unkempt canyonBOT
#

property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.
slate swan
#

!d discord.Role.permissions

unkempt canyonBOT
slate swan
pliant gulch
shrewd inlet
#

fixed it but still doesn’t work when i run it on discord

pliant gulch
#

It would be be a lot faster than what you got rn for that

#

As it is O(n) where the other would just be O(1)

slate swan
slate swan
slate swan
shrewd inlet
slate swan
slate swan
shrewd inlet
slate swan
shrewd inlet
#

ohh ty

slate swan
slate swan
#

a coroutine is an async function

#

its correct?

shrewd inlet
slate swan
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
slate swan
#

takes an argument

shrewd inlet
slate swan
#

not right

#

one is in the params of the event and the other is the one in the process commands coro

pliant gulch
slate swan
slate swan
#

because it returns a dict and doesnt take arguments?

#

CacheImpl.pokemon_cache is all you do

#

yeah ik

slate swan
#

i should do that for akeno lolll

#

idk if its good or not, but im trying to make most of the things as properties

#

i mean if it doesnt need to be called with arguments i think its fine

#

almost all functions which return a dict are properties there

#

yeah

pliant gulch
slate swan
#

god level cache incoming

pliant gulch
#

I do all that extra stuff to make the dict also act as as a sorta collections.deque without being a list

slate swan
pliant gulch
#

Thus allowing for a popleft at O(1) getitem instead of O(n) for list iteration

slate swan
#

bro chill with the time comps

#

i dont know them🏃

pliant gulch
#

You can just think of, O(1) being constant time, no matter how many items it will always be the same time

#

Then you can think of O(n) as linear time, the time goes up with the amount of items you are dealing with

slate swan
#

ahhhh so O(1) is constant time which never changes and O(n) is linear time which changes by amount?

#

and how would you know about it being constant or linear?

final iron
#

Well iterating through a list is O(n) right?

pliant gulch
#

yes

final iron
#

The more elements in the list, the longer it takes?

slate swan
#

yeah because you dont know how many items it has so the time changes

final iron
#

ahhhhhhhh