#discord-bots

1 messages Β· Page 851 of 1

hoary cargo
#

MR_uncanny_10 how can I efficiently compare time
I want to make something like if an user account Is older than 2 weeks kick his butt πŸ—Ώ
I didn't started working at this since I'm in my bed rn, but tomorrow I will and I need to know

sick birch
#

they're integers so it's efficient

slate swan
#

Where share codes😈😈

slate swan
hoary cargo
#

MR_uncanny_10 ok this sounds better than Unix maybe, I will try both methods

dull terrace
#

my database loading feels like absolute chaos

final iron
final iron
#

This will return unix time

#

Which you can subtract from whatever other unix time you want

#

Then you can format it with a timestamp

slim ibex
final iron
#

Here are the options for timestamp styles

dull terrace
final iron
slim ibex
#

first off you can use enumerate instead of range(len())

#

you return self but self isn't a param?

dull terrace
#

oh yeah, i've been meaning to start using enumerate for a while

#

idk about self, i haven't tested it yet

#

i mean to return it to the class attributes

slim ibex
#

this is a dataclass right?

dull terrace
#

yeah

slim ibex
#

classes still apply. all the principles from normal classes apply to dataclasses

dull terrace
#

yeah, new with classes in general so

#

i'm doing player = user.fetch(message.author.id)

#

so i need to send the tuple i created to user class

#

then return the user class to player

slim ibex
#

where do you do that?

dull terrace
#

idk, i haven't really figured that out yet, i just threw in self(*cache[bob])

#

like if the function fetch was outside the class i would just do player = user(*cache[bob]) and then return user to make it work

spring verge
#

I am using PIL and easypil for image generation and I realized that it takes like 4-5 seconds to generate a leaderboard image or rank card image

spring verge
#

anyone here who has worked with these libs and know how to make it takes less time?

dull terrace
slim ibex
#

well imma head to bed rn. i might try to test this rq

spring verge
dull terrace
#

i make a 7x8 tile with tons of alpha overlays and it takes less then 1/100th of a second with the rest of the code

spring verge
#

4000x2000

dull terrace
#

but resolution is 50x7x50x8

#

350x400

slim ibex
#

what does cache represent @dull terrace

dull terrace
#

also, discord downscales images

spring verge
dull terrace
#

so high res is kinda pointless

spring verge
dull terrace
#

idk what they downscale to but youll see the image size is way different from opening original

spring verge
#

so 4000x2000 probably should be like 800x400?

#

ok Imma change it to 800x400

#

imma go test that resolution

dull terrace
slim ibex
#

ok

slim ibex
#

im tryna figure out how i can replicate this in a simple way

dull terrace
spring verge
#

damnn

#

u also save the file to folder

#

and get it from there?

dull terrace
#

example image

spring verge
#

ooo

#

thats what u meant by 7x8

dull terrace
#

i save it to a temp file that's the same as user id and then upload that to my an aws and send the link then delete the temp one

#

i should just send the bytes directly but i couldn't get that working

slim ibex
#

@dull terrace

@dataclass
class Foo:
    def bar(self, baz):
        results = [1, 2, 3]

        something[baz] = results # unresolved refrence 'something'

        return self(*something[baz]) # 'Foo' object is not callable, unresolved refrence 'something'

idk if your code will work

dull terrace
#

circle back around to it soon

spring verge
slim ibex
#

you might have to implement a __call__ method to call the your class object

#

anyways imma go

dull terrace
#

yeah that's already what i'm doing right?

slim ibex
#

?

dull terrace
#

then im returning the tuple

slim ibex
#

are there any warnings or errors from return self(*cache[bob])

dull terrace
#

haven't tested yet, so much code to go through before then

slim ibex
#

is it like underlined or anything. does the IDE say anything about it

#

also for those dict types, prolly specify the type of the key and value

dull terrace
#

blacken doesn't say anything about it when i auto black my code, ide isn't much help apart from that

slim ibex
#

if it could be anything, typehint could be Dict[Any, Any]

dull terrace
#

hmmm

slim ibex
#

and that requires from typing import Dict, Any

#

anyways, next time we talk about this we should prolly go to OT

#

but imma head out now. gl

dull terrace
#

okay thanks dude, night

slim ibex
dull terrace
#

1 million images at 5mb = 5 tb of data

spring verge
#

I will try to figure that out once I fix this time thing ;-;

spring verge
#

oo only one line

#

so basically once the message with image is sent

#

u delete the image hmm

dull terrace
#

well i upload to amazon server and save the url

spring verge
#

thats why I over write it

#

in ur case ur saving images with different names , right?

dull terrace
#

hmm thatll be a problem

final iron
#

πŸ—Ώ

dull terrace
#

if one person gets the image generated, then another starts generating the image, itll send a blacked out image to the first person @spring verge

#

especially if the image gen is slow

spring verge
dull terrace
#

pil kinda saves the image like slow internet where it fills from the top

spring verge
#

;-;

dull terrace
#

yeah

#

or maybe block it somehow but thatll slow things down

spring verge
#

yea I dont wanna slow it down

#

anyways thx for the help .. if I get stuck somewhere is it ok to dm u?

#

or ping here?

dull terrace
#

although the save process might not actually be that slow, it would have to be mid save not generation

#

yeah ping here, pil is one of the few things i feel like i've got a decent grasp of

dull terrace
spring verge
#

nicee I feel pretty noob at pil so It will be a great help for me XD

dull terrace
#

πŸ€” this?

slate swan
#

I'd prefer doing it in the init dunder

final iron
#

πŸ—Ώ

dull terrace
final iron
#

Ignore what I said

spring verge
#

over here yPos is 20

#

RankNumberColumn[index] is '#1'

#

font1 is valid and color is (255,255,255,255)

#

and it doesnt print 1.5

#

so I think it errors on the line in between

dull terrace
#

hmm can you have alpha values in colour like that or is it just rgb

#

what's the error code

spring verge
#

well there is no error code 0-0 .. also the code worked before I divided every pos thing by 5

#

cuz 4000x2000 is now 800x400

dull terrace
#

so you're just not seeing the text on the image?

spring verge
#

nope I mean bot keeps thinking

#

no image is generated

#

this is the only output .. dont mind those print values

dull terrace
#

that's weird, i would assume an infinite loop somewhere if it's just not doing anything

spring verge
#

oh I am not using while loop anywhere tho

#

its only for loops

dull terrace
#

or you messed up a value somewhere by 10x and it's trying to make a huge image

spring verge
#

hmmmm

slate swan
dull terrace
#

my text gen code for comparison

slate swan
#

The way you define image ,or the loop if any

spring verge
spring verge
dull terrace
#

i've never had the problem you're describing, but i've always made very small images. if you can hear your computer fan whirring it's definitely struggling to draw something

spring verge
#

o

dull terrace
#

although text can't be that hard to draw

spring verge
#

I reverted back to 4000x2000 code to see where I made the wrong change .. hope I find the bug xd

echo wasp
#

error (picture) code: ```py
def convert(time):
pos = ["s","m","h","d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600 , "d" : 3600*24}

    unit = time[-1]

    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2


    return val * time_dict[unit]
spring verge
#

so should I assume its cuz I am drawing lot of stuff

#

I think I will have to share the code ;-;

vast gale
#

@spring verge it's probably taking a while and is blocking, how long are you letting it run that single line of code

echo wasp
#

Any idea on how to solve my issue?

dull terrace
quick gust
#

where's your convert function, inside another command or...?

spring verge
dull terrace
#

how do i fill in values without resorting to f strings here

#

for the ? regarding a column name

spring verge
#

oh I use asyncpg

#

and we just directly put it after comma .. like

#

so $1 is replaced by ctx.options.title

#

$2 by description and so on

#

which sql lib r u using?

dull terrace
#

yeah works the same here except when you try to replace a column name value

#

sqlite3

spring verge
#

o

quick gust
#

what's id?

spring verge
#

in asyncpg u cant actually put table name with parameter values

dull terrace
#

trying to do this

spring verge
#

so probably sqllite3 has similar issue ?

quick gust
#

if it's a user ID then you can use f strings I believe

spring verge
dull terrace
#

eh f strings work and it's not a user input so should be fine

quick gust
#

yeah, there must be another way though

dull terrace
#

you'd think so

spring verge
#

there is no parameterization way for "table name" in asyncpg

dull terrace
spring verge
#

will sql injection problem get prevented?

dull terrace
#

basically recommending to do it my way here

spring verge
#

cuz we dont use f string because of the sql injection problem

maiden fable
#

Not the second one

dull terrace
#

seems like f strings are good

spring verge
maiden fable
spring verge
#

she is not using for values

#

table names or column names cant be replaced by parameterization

dull terrace
#

well they're saying here they never bothered implementing placeholders for column names because there's no safety risk

maiden fable
#

She?

echo wasp
dull terrace
#

he

spring verge
#

he*

maiden fable
#

Ah okay

spring verge
#

parameters for values

maiden fable
#

For?

spring verge
#

and f string for table/column names

slate swan
echo wasp
#

Hunter can you tell me how I fix my convert issue?

maiden fable
#

Like, mind giving me an example. I ain't following the convo

maiden fable
slate swan
#

lol same

spring verge
#

f'SELECT * FROM {table} WHERE user_id = $1' , ctx.author.id

maiden fable
#

Noooo

#

Wait

#

Who's setting the table?

#

You or it can be anyone?

spring verge
# maiden fable Noooo

so how will u replace table name in asyncpg when u cant put parameter value for it

slate swan
spring verge
maiden fable
#

Ah then it's fine

spring verge
slate swan
#

since when?

spring verge
#

what

slate swan
#

wasnt place holders % ?

spring verge
#

I have been using it for decades

slate swan
#

only 2 symbols

dull terrace
#

i've been using ? for placeholders lol

spring verge
#

pls read that I use asyncpg

#

not sqlite3

maiden fable
slate swan
slate swan
maiden fable
#

That's a way for string formatting

slate swan
#

what the %

maiden fable
#

The % sign

slate swan
#

ye

maiden fable
#

Yea...

slate swan
#

i thought it was a placeholder lol

maiden fable
#

It's used for string formatting, just like f strings or format method

spring verge
spring verge
#

I think its prob a bad practice

#

hmmm Idk man I will try to improve

#

anyways its only getting set by me so I can ignore it for now

echo wasp
#

Any luck of solving my issue?

spring verge
#

so there is no problem with pil or easypil ;-;

#

like pil work starts after arranging loop data

dull terrace
#

what kind of leaderboard are you making?

#

that has that much data

spring verge
#

lemme share the code

quick dust
#

anyone know what is going wrong?

429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.

no idea why

slate swan
#

read the error

quick dust
slate swan
#

youve been ratelimited

dull terrace
spring verge
#
    RankNumberColumn = []
    AvatarColumn = []
    UsernameColumn = []
    DiscriminatorColumn = []
    HighscoreColumn = []
  
    finalRange = 5
    userRank , userHighscore = None , None
    for index , row in enumerate(rows):
      if row['user_id'] == ctx.author.id:
        userRank = index+1 
        userHighscore = row[game]
      if index < 5:
        finalRange -= 1
        userObject = await ctx.bot.rest.fetch_user(row['user_id'])
        if userObject.avatar_url is not None:
          pfp = await load_image_async(str(userObject.avatar_url))
        else:
          pfp = await load_image_async(str(userObject.default_avatar_url))
        print(time.time() - start_time)
        data = Editor(pfp).resize((256,256)).ellipse((0,0),256,256,stroke_width=0).circle_image().image_bytes
        print(time.time() - start_time)
        if len(userObject.username) > 15:
          UsernameColumn.append(f"{userObject.username[:12].strip()+'...'}")
        else:
          UsernameColumn.append(f"{userObject.username}")
        RankNumberColumn.append(f'#{index+1}')
        AvatarColumn.append(data)
        DiscriminatorColumn.append(f"#{userObject.discriminator}")
        HighscoreColumn.append(row[game])```

this might be bad code (wrote it many months ago)
subtle dirge
#

No

#

Like what in his code is causing that

dull terrace
#

how many users are you fetching?

subtle dirge
dull terrace
#

oh 5?

spring verge
#

and appending the user data to it

#

and access it when doing image stuff with pil

slate swan
#

guys this is kinda ot ngl

spring verge
#

ot means

slate swan
#

off topic

quick dust
spring verge
#

kinda confused here ;-;

quick dust
#

not mine

dull terrace
#

idk im looking at it and trying to see what's slowing it down. if you're fetching hundreds of users that's a really bad idea

slate swan
#

i wonder why youre getting ratelimited

slate swan
#

isnt that img manipulation?

spring verge
#

but isnt the code related to discord bots?

dull terrace
#

5 shouldn't be that much of a problem

slate swan
#

Β―\_(ツ)_/Β―

spring verge
#

technically that code doesnt even have any manipulatuion except one line of code

#

its just getting user data

#

so its like 50-50 idk

tacit storm
#

we wont help with shit that goes against tos

slate swan
spring verge
dull terrace
spring verge
#

ye

dull terrace
#

try not doing that and see what happens, curious

slate swan
dull terrace
#

just keep square images

spring verge
#

it takes like 0.04 s

#

before that and after that code

#

so shouldnt be a problem..ig

dull terrace
#

how high is your ping?

spring verge
dull terrace
#

if it's taking you 500ms to fetch each user that might be the problem

spring verge
spring verge
quick gust
#

@echo wasp is your issue fixed

dull terrace
#

try ping command for discord

quick gust
#

Im guessing you have the convert function inside a command so it doesn't work outside other commands

echo wasp
dull terrace
#

if it's not that the only other thing it could be is this function and whatever it's doing i think:

  pfp = await load_image_async(str(userObject.avatar_url))
else:
  pfp = await load_image_async(str(userObject.default_avatar_url))```
#

are you downloading the profile pictures?

#

you must be for pil, if the pfp image is large then that could slow things a lot, but i thought discord limited size

spring verge
#

Imma tell u in few mins (currently on phone)

#

Btw kinda off topic again but how's the code in your opinion? Is it badly written xD?

slate swan
#

Can't see anything wrong with it other than the fact that it Doesn't follow Pep8

dull terrace
#

variable names could be a lil clearer and when you +1 you should leave spaces either sides of the + usually but i haven't got much more advice than that because my code is monstrous

#

the commas too should be like, this, where, no, space, before,

maiden fable
slate swan
spring verge
spring verge
#

these are outputs for those 3 print statements

#

seems like fetchrow is taking lot of time as well hmm

#

I think I will have to remove the use of it

#

and 0.3 seconds for the pfp generation

dull terrace
#

what's your ping

#

bot.latency / client.latency and print

#

fetching 5 users should be pretty fast

slate swan
#

thats the latency on a ack heartbeat

dull terrace
#

should give some indication on the connection to discord servers tho

slate swan
#

It's heartbeat_latency.

#

yup

#

so you know whats the estimated latency on a ack heartbeat

slate swan
#

Nah I mean, it's not bot.latency, it's bot.heartbeat_latency

#

For them

slate swan
#

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

yup

slate swan
#

ah

spring verge
#

I am using hikari lightbulb :)

slate swan
#

ah nice

#

just print bot.heartbeat_latency it would be your latency in seconds

spring verge
#

Oke

slate swan
#

If it's over 0.05 stuff like sending images would be slow

#

Depending upon the size of image

spring verge
#

its um

#

0.3

slate swan
#

that's 300ms

spring verge
#

ye

#

wait so my code is fine?

slate swan
#

Seems like that

#

Does the image get saved?

spring verge
spring verge
slate swan
#

what's the size of the file?

#

Which gets saved

spring verge
#

800x400 resolution

slate swan
#

I mean, in kbs/mbs

spring verge
#

15.3

#

kb

slate swan
#

it should be uploaded in not more than a second then

#

How do you send it?

spring verge
#

yep 0.1ms

spring verge
#

the most time is taken before saving btw

slate swan
#

It's because you run a loop which may be taking a long time

spring verge
#

like 3 seconds goes to other stuff before beginning image manipulation

spring verge
#

which is not good?

slate swan
#

Thats just like your internet connection, nothing to do with your code other than sending/recieve data

#

!d discord.Guild.edit

unkempt canyonBOT
#
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the guild.

You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.

Changed in version 1.4: The rules\_channel and public\_updates\_channel keyword-only parameters were added.

Changed in version 2.0: The discovery\_splash and community keyword-only parameters were added.

Changed in version 2.0: The newly updated guild is returned.
spring verge
dull terrace
#

fetching 5 users would be at least 1.5 seconds

spring verge
#

so half of time is going there?

brazen raft
#

Yeah, Discord doesn't allow that. You could transfer the ownership to the bot, maybe, or have your bot create a new guild

dull terrace
#

hold on ill check my ping to compare

#

mines 0.1

#

and i consider my connection to not be too fast

spring verge
#

Hmm but it takes u like only 0.5s to get image

slate swan
spring verge
dull terrace
#

yeah, i mean does your code actually need to fetch users

#

there must be a way around that

spring verge
#

Yea Imma look for that

dull terrace
#

you could save profile urls to a database whenever someone interacts with your bot if you had to

spring verge
#

btw either I can do get_user or fetch_user

#

if I want to get full user object

#

get_user wont work always

#

cuz it gets user object from bot cache

dull terrace
#

avatar url

spring verge
#

but what if person changes their avatar

#

wait u mean

#

I should store their name etc everything

#

everytime they invoke a command]

slate swan
dull terrace
#

it's only for their highscore, it can be a little out of date

slate swan
#

!d disnake.ext.commands.Bot.getch_user

unkempt canyonBOT
#

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

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
dull terrace
#

everytime they invoke a command, check if you have their avatar or if it's been a certain length of time and save it if conditions met

slate swan
#

pretty handy in disnake

dull terrace
#

for the people using the bot enough to get on the leaderboard i imagine they're interacting with the bot often anyway

spring verge
#

hmm true

brazen raft
#

No, it's the opposite. Imagine inviting a bot only to get your server deleted, and being sent scams

echo wasp
#

what do i need to supply to thease args? (self, ctx, mins : int, * , prize: str)

dull terrace
#

g"\/"

#

it's a g string

slate swan
#

Why didn't they just call it get_or_fetch

slate swan
#

its an alias

#

!d disnake.Client.get_or_fetch_user

unkempt canyonBOT
#

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

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
echo wasp
#

can someone tellme what args i need to supply the command? for it to work?

slate swan
#

oh ok

slate swan
maiden fable
slate swan
small igloo
#

ok, how to remotely cooldown a ppl πŸ—Ώ

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

Lmao

slate swan
#

anyone know why?

#

I mean you can try checking the length of str(guild.roles), it's probably above 1024 characters

#

What are you trying to accomplish though?

#

Like do you want the guild's roles to be listed? As mentions or ID's?

#

just to show server info

spring verge
maiden fable
#
[role.name for role in guild.roles]
quick gust
novel bolt
# slate swan anyone know why?

if u just want to show all roles u can do like make a new list of roles roles=[role.mention for role in ctx.guild.roles] and then change value =','.join(roles)

slate swan
maiden fable
slate swan
#

=== in js exists because == does type conversion

'1' == 1;
// This is true

'1' === 1;
// This is false
maiden fable
#

So the @unkempt canyon and other bots are moving to disnake for the time being πŸ‘€

lusty yew
#

So I want to use the open and the read functions to my Discord bot to recognize if someone did already used a command or claimed a username (for a Minecraft server). If someone uses the command it will be logged in a txt file separated for the Discord user ids and the usernames what people gave. I used the if variable so if one of them in the txt file, the user will get an error message. The problem is that I can't recognize the 2 variable at once because only this first one works.

placid skiff
placid skiff
lusty yew
#

And it's almost done this is the only one problem with it

placid skiff
#

i don't understand your problem lol

maiden fable
placid skiff
#

Lol didn't read it yet

mental escarp
#

Hello. Has someone seen a good tutorial for transcripts on a Website for modmails? Feel free to ping me

slate swan
#

anyone know why?

#

the guild is underlined

placid skiff
#

because you have no variables called guild

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

slate swan
#

and why the heck is client coloured like a class

maiden fable
#

Like the default color of a class object

slate swan
#
class Bot(commands.Bot):
  def __init__(self, Bot):
    return Bot
@Bot.event

is invalid

small igloo
maiden fable
maiden fable
small igloo
slate swan
maiden fable
maiden fable
# small igloo πŸ—Ώ nope
def bypass_for_owner(message):
    # Bypasses cooldown, no cooldown for this specific user
    if message.author.id == owner_id:
        return None
    # Otherwise cooldown of 1 per 1 second
    return commands.Cooldown(1,1)

@commands.dynamic_cooldown(bypass_for_owner)
@bot.command()
async def cmd(ctx):
    await ctx.send("test") 
slate swan
#

🀨

maiden fable
#

U r missing a comma

slate swan
#

oh

maiden fable
#

After intents=intents

slate swan
#

yea i see it now πŸ’€

small igloo
small igloo
maiden fable
small igloo
maiden fable
maiden fable
small igloo
slate swan
#

also, why arent giphy/tenor links loading in embeds ;-;

small igloo
maiden fable
#

What's the url u setting?

slate swan
#

you need to go to the site, and copy the real url from there

maiden fable
#

Yes

slate swan
#

yeah I did that

#

the one you send from discord wont work

#

mind showing the gif?

#

I went to the official gihpy websitee

slate swan
small igloo
maiden fable
maiden fable
slate swan
#

why do i see js everywhere πŸ˜”

maiden fable
#

https://giphy.com/gifs/PHZ7v9tfQu0o0 idk this URL is what u using?

slate swan
#

https://media2.giphy.com/media/PHZ7v9tfQu0o0/giphy.gif

maiden fable
#

O

slate swan
small igloo
maiden fable
#

Bro

small igloo
slate swan
#

huh

small igloo
#

asdf, wait why mp4

slate swan
slate swan
#

sorry for the ping m8 πŸƒβ€β™‚οΈ

small igloo
small igloo
slate swan
#

I dont have that url

#

smh

small igloo
slate swan
small igloo
#

and the very last thing in the url, is the real url

#

ig

slate swan
slate swan
#

oh lmao

#

you will get the link i sent

maiden fable
slate swan
slate swan
# small igloo waht
def bypass_for_owner(message):
    """
    assume this is something like a cooldown generator 
    you can have conditions which can return Cooldown values using 
    `commands.Cooldown(times, per, bucket)`
    returning None would mean that there's no cooldown
    """
    ...

@commands.dynamic_cooldown(bypass_for_owner)
@bot.command()
async def cmd(ctx):
    await ctx.send("test") ```
small igloo
slate swan
#

read it

small igloo
#

understand

slate swan
#

or ill write a novel again

small igloo
spring verge
#

yo

spring verge
#

and still taking 2 secs for 5 user ids

#

idk how do I resolve this aaa

slate swan
#

everything else remains same

small igloo
slate swan
#

the cooldown variable there is the bypass_for_owner function

slate swan
small igloo
slate swan
small igloo
slate swan
#

!d discord.ext.commands.Command.update

unkempt canyonBOT
#

update(**kwargs)```
Updates [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") instance with updated attribute.

This works similarly to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator in terms of parameters in that they are passed to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or subclass constructors, sans the name and callback.
slate swan
#

takes a cooldown kwarg

small igloo
spring verge
#

I just realized I dont know how to cache data

slate swan
#

how do you use getch then?

nimble plume
#

.

hallow tangle
#

how to add options in slash commands (disnake)

spring verge
#

if it returns None I fetch?

slate swan
#

it means that the user_id is not in the cache

#

do you have member intents?

spring verge
hallow tangle
unkempt canyonBOT
#

examples/slash_commands/old.py lines 11 to 24

@bot.slash_command(
    name="slash_command",
    description="A Simple Slash Command",
    options=[
        disnake.Option("string", description="A string to send", required=True),
        disnake.Option(
            "channel", description="The destination channel", type=disnake.OptionType.channel
        ),
        disnake.Option(
            "number", description="The number of repetitions", type=disnake.OptionType.integer
        ),
    ],
)
async def command(inter, string, channel=None, number=1):```
slate swan
#

string, channel and number will be options there

hallow tangle
#

I want a menu like this

hoary cargo
#

Those are params

hallow tangle
#

names are options

#

pokemon is param

hoary cargo
#

Dude

#

commands.Param .

slate swan
hallow tangle
spring verge
hallow tangle
#

fine

spring verge
#

just telling cuz there are lots of pokemon

slate swan
hallow tangle
#

I'm not copying that bot, it was an example

hoary cargo
slate swan
#

^^^

spring verge
#

what I dont get is if I check my ping normally

#

its 26ms but when I print the latency in code then its 300ms

slate swan
#

Cache doesn't depend on your latency.

hallow tangle
#

ohh thanks

spring verge
spring verge
#

so should I really worry about the code ?

#

Idk if I really need get etc

hoary cargo
#

🀨

hallow tangle
#

how can I respond with different messages when different option is selected?

slate swan
spring verge
slate swan
spring verge
#

so should take like 1/4th time damn

#

1/3rd of 3 seconds is good already

slate swan
#

For my replit it's 32 ms and works decent

spring verge
#

so I can expect bot to reply within a second 0-0 instead of in 3-4 secs

slate swan
hoary cargo
spring verge
#

ok Ig I wont worry about the fetch and PIL code

#

thx for the help

hoary cargo
#

MR_uncanny_10 me paying just 1,5$ for host and have a 20-30ms latency

quick gust
#

me not paying for a host and getting 35ms

spring verge
#

howw

quick gust
#

:)

spring verge
#

my bot gets 300ms and when I test on google I get 26ms

#

I still dont understand the difference

quick gust
#

doesn't matter, i get 6 ms normally and 350 ms when I run the bot from my pc

spring verge
placid skiff
# spring verge

local ping that you measure from speed test is different from the ping you get somewhere else

slate swan
#

ah no

quick gust
#

yeah, I am not paying for an online host my bot runs on. but when I run it on my pc it's always above 300

placid skiff
#

there are other variables to consider, like the distance between the server you are trying to connect and your router, avg speed of the server

spring verge
quick gust
#

no

placid skiff
#

They take discord servers .-.

spring verge
#

now I get it me dumb

placid skiff
#

you connect to discord API

spring verge
#

ye Idk why I expected it to connect to same server like normally

#

anyways thx my doubt got cleared :)

quick gust
#

max I've reached is 1200 ms when running my bot locally lmao

cloud dawn
placid skiff
#

i never reached latency those high locally D_D

haughty quartz
#

how can i get a message object by id

#

(i would use it to update the bot's message)

hallow tangle
# hoary cargo ```py if var_name == "choice name": . . . Do stuff ```

I tried doing this, it doesn't responds ```py
Party = ['Watch Together', 'chess']

async def autocomplete_langs(inter, string: str) -> List[str]:
return [lang for lang in Party if string.lower() in lang.lower()]

@bot.slash_command()
async def activity(inter: disnake.CommandInteraction,channel: disnake.VoiceChannel ,Party: str = commands.Param(autocomplete=autocomplete_langs)):
if Party == "Watch Together":
invite = await channel.create_invite(target_type=disnake.InviteTarget.embedded_application, target_application=disnake.PartyType.chess)
await inter.response(f"Click to open Watch Together in {channel}")
elif Party == "chess":
invite = await channel.create_invite(target_type=disnake.InviteTarget.embedded_application, target_application=disnake.PartyType.chess)
await inter.response(f"Click to open Chess in {channel}")```

placid skiff
placid skiff
slate swan
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
placid skiff
unkempt canyonBOT
quick gust
#

!d discord.abc.Messageable.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
placid skiff
#

what were you sayin?

haughty quartz
#

i see there are differnt ways of doing this

slate swan
quick gust
placid skiff
slate swan
#

No they don't

quick gust
#

since most people either use dpy or other forks

haughty quartz
#

i use disnake either way

spring verge
placid skiff
slate swan
quick gust
haughty quartz
#

alr thanks guys!!

spring verge
#

Btw hikari and disnake are currently most popular?

placid skiff
#

get_message method search the id from the bot chace

quick gust
placid skiff
#

he needs to use fetch_message

#

from messageable or from the channel

haughty quartz
#

? why do i need to use that?

slate swan
haughty quartz
#

i could get message and message.edit

placid skiff
haughty quartz
#

oh

placid skiff
#

bot cache is deleted whenever you turn the bot off

haughty quartz
#

that might be a issue

quick gust
#

yeah just fetch the message from messageable if you don't have the channel object

#

else, fetch it from the channel

spring verge
placid skiff
#

yup, you have to use the fetch method from messageable or a channel object

quick gust
haughty quartz
#

i'll fetch it then

placid skiff
hoary cargo
haughty quartz
#

my code is a mess, i dont have a command handler and about 600 lines lmfao

spring verge
slate swan
slate swan
#

!pip hikari-lightbulb

spring verge
#

^

unkempt canyonBOT
slate swan
#

!pip hikari-tanjun

unkempt canyonBOT
spring verge
#

Tanjun is 2nd

#

Yea

slate swan
#

And one more but IDR it

placid skiff
spring verge
#

For component handler we have 2 iirc

#

One of them is miru

placid skiff
#

btw never needed to use them

slate swan
spring verge
#

Damn 2.0 is op

spring verge
placid skiff
spring verge
#

Just use implementation and bam u r done

slate swan
#

And it makes you a slash help command by subclassing the Help class , which I don't think any fork does

placid skiff
slate swan
#

oh? Docs pls

spring verge
placid skiff
#

with slash commands you just check which one of the two option are passed in the parameter

slate swan
spring verge
# placid skiff docs tells use

Ofc they do? But how does ur point explain? Like Ik how to use get and fetch together but Idk when I can expect for user to be stored in cache

#

Basically I have no problem with the use but problem with the procedure before you are able to use it

#

I hope I make sense ;-;

slate swan
#
@command
@option(name1, desc)
@option(name2,desc)
@implements(PrefixCommand, SlashCommand)
async def foo(ctx):
   ....```
#

the first option can be accessed using CTX.options.name1, and the other one with CTX.options.name2

#

for the normal command one can use the CONSUME_REST modifier Along with it

placid skiff
#

message are stored in the cache when they are sent and the bot can see them

spring verge
placid skiff
spring verge
#

Now let's say command invocation event for example

#

Or any other event I don't mind.. so as soon as the event takes place

#

Bot will store in cache automatically?

placid skiff
#

yes

spring verge
#

So for command invocation event let's say I invoked a command

spring verge
#

The event runs as well.. but still get_user returns None

#

and I didn't turn off the bot as well

placid skiff
placid skiff
spring verge
#

Inherited from Cache.get_user

#

Or I misunderstood u

placid skiff
# slate swan <@704973651698778225>

let's make an example:

from disnake.ext.commands import *
from disnake import ApplicationCommandInteractions

class test(Cog):
  def __init__(self, bot):
    self.bot = bot

  @slash_command()
  async def test(ctx: ApplicationCommandInteractions, a: str, b: str):
    await ctx.send(a+b)

def setup(bot):
  bot.add_cog(test(bot))

With a normal command you can't do this without a separator for the two strings, the same command make without slash_command will became a complete different command because you will have only one parameter and you will need a separator

#

so it will be like writing the same operation two times

#

no time gained at all at level of coding and lines of code

slate swan
#

Β―_(ツ)_/Β―

#

how do you mention option descriptions in disnake?

#

without that old options arg in the deco

spring verge
#

Damn 1v1 going intense

#

Btw whenever it's done.. tell me.. I still need to discuss about get_user lol

placid skiff
#

the prefix command? he can't lol, for a prefix command only the "a" option will be passed

spring verge
#

String parsing go brrr

slate swan
#

its apparently like py @slash_command() async def test(ctx: ApplicationCommandInteractions, a: str, b: str): await ctx.send(a+b) @command() async def test2(ctx: commands.Context, a , b): await ctx.send(a+b)

#

combined

placid skiff
#

ok, test that command and pass something like this a="i like" b="coding with other people"

placid skiff
slate swan
placid skiff
slate swan
#
@option("b", "description", modifier = CONSUME_REST)``` DOES it all , without conflicting with the slash command.
#
@option("b", "description", modifier = CONSUME_REST)``` DOES it all , without conflicting with the slash command.
placid skiff
slate swan
light violet
#

msg = "750015265135263835"
user = discord.User(msg)
@client.event
async def on_ready():
print("I'm in")
print(client.user)
await user.send("hy success yeh")

placid skiff
#

What you didn't get of "undefined length"? πŸ˜‚ πŸ˜‚

light violet
#

not working help

placid skiff
light violet
#

lol

#

i nmed it msg

placid skiff
#

That's not how converter works lol

light violet
#

just

placid skiff
#

You have to use fetch or get method

light violet
#

how

placid skiff
#

!discord.ext.commands.Bot.get_user

#

Failed

light violet
placid skiff
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
light violet
#

o it

#

@placid skiff not in mutual servers of mine or it

placid skiff
#

It will work in all guild...

light violet
#

bot not present in any guild

#

just rndom

placid skiff
#

It will work anyway πŸ˜‚ πŸ˜‚

light violet
light violet
#

msg = "750015265135263835"
user = client.get_user(msg)
@client.event
async def on_ready():
print("I'm in")
print(client.user)
await user.send("hy success yeh")

this?

placid skiff
#
user: discord.User = client.get_user(your_id) 
#your event here
#

The id must be an int, not a string

light violet
#

ok

placid skiff
light violet
#


Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/runner/massive/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 12, in on_ready
await user.send("hy success yeh")
AttributeError: 'NoneType' object has no attribute 'send'

#

msg = '750015265135263835'

@client.event
async def on_ready(user: discord.User = client.get_user(msg)):
print("I'm in")
print(client.user)
await user.send("hy success yeh")

placid skiff
light violet
honest vessel
#

prob not cached yet

placid skiff
#

nah get_user doesn't need cache i think

light violet
slate swan
light violet
#

with this

placid skiff
slate swan
#

yea so?

#

how does that matter

placid skiff
#

but you don't know the length of the string untill the string is sent

light violet
#

;

placid skiff
slate swan
light violet
quick gust
placid skiff
#

get it now?

light violet
#

ok got it

quick gust
slate swan
#

or do you mean splitting with ;?

placid skiff
#

with slash command is simple because i don't need to separate them with a separator

light violet
placid skiff
#

if I used a prefix command i had to separate all those strings

slate swan
maiden fable
placid skiff
light violet
maiden fable
#

Use tasks.loop and set the count to 1

light violet
#

docs

maiden fable
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
light violet
#

ok lemme try

placid skiff
#

a is a string

slate swan
#

no

#

recheck what you wrote there..

#

should be *,a

placid skiff
#

lol my bad

#

but the point is the same

light violet
#

;

gaunt ice
#

i aint getting any error or anything

#

wait

light violet
#

?? this??

quick gust
#

no, just the time seconds=1

light violet
#

wott bout tsk?

quick gust
#

then inside your function, do what you were doing in on_ready

quick gust
#
@tasks.loop(seconds=1)
async def send_task():
    #code here```
light violet
#

msg = "750015265135263835"
user = client.get_user(int(msg))

@client.event
async def on_ready():

print("I'm in")
print(client.user)

@tasks.loop(seconds=1)

quick gust
#

no tasks.loop is a decorator

light violet
#

how to send tsk?

quick gust
#

Remove @client.event and on_ready

light violet
#

ok

#

then

light violet
#

this?

quick gust
#

yes and now start the task

light violet
#

how to srts

#

;

quick gust
#

send_task.start()

light violet
#

ok

quick gust
#

i think its called, not sure

light violet
#

ok

#

I'm in
None
Unhandled exception in internal background task 'send_task'.
Traceback (most recent call last):
File "/home/runner/massive/venv/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "main.py", line 17, in send_task
await user.send("hy success yeh")
AttributeError: 'NoneType' object has no att

maiden fable
light violet
quick gust
#

what?

maiden fable
light violet
#

ok

maiden fable
quick gust
#

idk i haven't really used tasks lmao, but yes makes sense. it will stop after doing it once right?

maiden fable
#

Yes

light violet
#

handled exception in internal background task 'send_task'.
Traceback (most recent call last):
File "/home/runner/massive/venv/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "main.py", line 17, in send_task
await user.send("hy success yeh")
AttributeError: 'NoneType' object has no attribute 'send'
^CξΊ§

quick gust
#

show your code

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

light violet
#

msg = "750015265135263835"
user = client.get_user(int(msg))

@tasks.loop(seconds=1)
async def send_task():
await client.wait_until_ready()
print("I'm in")
print(client.user)
await user.send("hy success yeh")

send_task.start()

maiden fable
#

Bro

quick gust
#

.. you are trying to get the user before the cache is ready, put it under the wait_until_ready

maiden fable
#

Get the user inside the function

light violet
#

ok

#

Unhandled exception in internal background task 'send_task'.
Traceback (most recent call last):
File "/home/runner/massive/venv/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "main.py", line 18, in send_task
await user.send("hy success yeh")
AttributeError: 'NoneType' object has no attribute 'send'

#

@tasks.loop(seconds=1)
async def send_task():
await client.wait_until_ready()
print("I'm in")
print(client.user)
msg = "750015265135263835"
user = client.get_user(int(msg))
await user.send("hy success yeh")

placid skiff
light violet
#

just experimenting

light violet
#

;

light violet
placid skiff
#

you need to learn more to develop bots
also there are some basic examples of discord.py on the internet which explains you the basics of the package

light violet
#

i knoe discord py

#

;

#

little bit

placid skiff
#

If you knew you should know the problem with your code .-.

light violet
#

........

slate swan
placid skiff
#

we are helpin' him for half an hour lol

slate swan
light violet
#

ok

light violet
cloud dawn
placid skiff
#

i didn't ask him to stop askin lol

small igloo
#

ok, how 2 make random death phrases, i try dis but it's says that too few args πŸ—Ώ

AE = random.randint(0, len(deathPhrases))
d.add_field(name=f":crossed_swords: {deathPhrases[AE]}".format(hurter, hurted))```
cloud dawn
light violet
#

Unhandled exception in internal background task 'send_task'.
Traceback (most recent call last):
File "/home/runner/massive/venv/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "main.py", line 17, in send_task
await user.send("hy success yeh")
AttributeError: 'NoneType' object has no attribute 'send'

light violet
#

@slate swanfrom discord.ext import commands, tasks
i = discord.Intents.all()
client = discord.Client(intents = i )

@tasks.loop(seconds=1)
async def send_task():
await client.wait_until_ready()

msg = "750015265135263835"
user = client.get_user(int(msg))
await user.send("hy success yeh")

send_task.start()

small igloo
cloud dawn
#

!e ```py
import random

for x in range(4):
print(random.choice(["yes", "no"]))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

001 | no
002 | no
003 | yes
004 | no
visual island
light violet
# slate swan yea that should work

Unhandled exception in internal background task 'send_task'.
Traceback (most recent call last):
File "/home/runner/massive/venv/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "main.py", line 17, in send_task
await user.send("hy success yeh")
AttributeError: 'NoneType' object has no attribute 'send'

small igloo
light violet
#

still

visual island
#

actually, choose 1, f-string or .format(), not both

visual island
#

add_field(name=..., value=...)

small igloo
small igloo
cloud dawn
light violet
small igloo
slate swan
slate swan
#

Then it won't work

light violet
#

i ws trying to do tht only dm with out mutuls

visual island
#

use fetch_user

vast gale
light violet
#

ok

small igloo
visual island
#

works even when the user doesn't have mutual guilds with the bot

cloud dawn
#

Use getch if you're using disnake.

small igloo
light violet
vast gale
visual island
visual island
cloud dawn
small igloo
visual island
small igloo
cloud dawn
small igloo
visual island
small igloo
small igloo
visual island
#

no

#

just that line

small igloo
small igloo
# visual island just that line

d.add_field(name=f"βš”οΈ {random.choice(deathPhrases)}".format(hurter, hurted), value="{}'s life {}/{}, {}'s life {}/{}".format(hurted, hp2, max2, hurter, hp, max))

gtg eat

visual island
#

then use the .format() like random.choice(deathPhrases).format(hurter, hurted)

brazen raft
#

Still, no.

visual island
#

{0} hurting {0} also string formatting uses 0 if i'm not mistaken

#

oh it doesn't matter, my bad

brazen raft
#

f-strings exist

visual island
#

deathPhrases=["{} hurting {}", "{} poking {}"] for this case it won't work

steel void
#

How can I modify variables inside of a button callback that are outside the button callback itself besides using a mutable data type such as a list or dictionary? I've tried using the global keyword but to no success.

#

im using pycord

visual island
#

cause you're formatting a string which exist already

brazen raft
steel void
#

im literally so lost

cloud dawn
cloud dawn
#

Don't think a button is tied to his bot var.

visual island
steel void
#

I want to be able to update a variable such as my_number = 0 but update it inside of the button callback like my_number += 1

brazen raft
#

Right, although you could just do an f-string on a where a is just " hurting "

cloud dawn
steel void
#

currently not using oop

brazen raft
#

They are both just as flexible, but f-strings are shorter to write

cloud dawn
brazen raft
#

What do you mean?

cloud dawn
#

Imagine he wants something2 before something because of a different death sentence.

visual island
#

you guys don't get it,

a = ["{} hurting {}"]

@bot.command()
async def foo(ctx, user):
  await ctx.send(a[0].format(ctx.author, user))
``` this is how you do it with `.format()`, how about f-string? (The `a` variable should be outside the command tho)
slate swan
#
a = ["$author hurting $target"]
@bot.command()
async def foo(ctx, user):
  await ctx.send(a[0].replace("$author", ctx.author).replace("$target" , user))``` πŸƒβ€β™‚οΈ
cloud dawn
cloud dawn
#

What if you want the user first and not ctx.author?

visual island
#
a = ["{1} hurting {0}"]

@bot.command()
async def foo(ctx, user):
  await ctx.send(a[0].format(ctx.author, user))
``` now it's user first
slate swan
#

was just a "not really" thing lol

maiden fable
#

Just give me one. fucking. reason. why I shouldn't hate u

visual island
#

fixed πŸ™‚

slate swan
tidal hawk
#

Passing context as: ctx: commands.Context is really old right?

slate swan
#

no?