#discord-bots
1 messages Β· Page 851 of 1
Can you just minus the time?
datetime
subtract the unix timestamps
they're integers so it's efficient
Where share codesππ
You can substract User.created_at from the current datetime which gives you a timedelta object, and you can use .days on it
ok this sounds better than Unix maybe, I will try both methods
my database loading feels like absolute chaos
πΏ
You can use .timestamp() on created_at
This will return unix time
Which you can subtract from whatever other unix time you want
Then you can format it with a timestamp
yeah a lot here could be fixed
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Here are the options for timestamp styles
π idk how else to do it
At least your tables can't get dropped
first off you can use enumerate instead of range(len())
you return self but self isn't a param?
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
this is a dataclass right?
yeah
classes still apply. all the principles from normal classes apply to dataclasses
wdym
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
where do you do that?
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
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
ok
anyone here who has worked with these libs and know how to make it takes less time?
wtf resolution are you using,
well imma head to bed rn. i might try to test this rq
very high ;-;
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
4000x2000
what does cache represent @dull terrace
also, discord downscales images
but that wouldnt be very clear , right?
so high res is kinda pointless
AA
idk what they downscale to but youll see the image size is way different from opening original
so 4000x2000 probably should be like 800x400?
ok Imma change it to 800x400
imma go test that resolution
um it's just a basic caching mechanism, every time i need to pull someones data i add them to the dictionary to keep it at ready and reset timer to 5 minutes before deleting
ok
btw was this message for me?
im tryna figure out how i can replicate this in a simple way
yes, pil gets my image in 1/100th of a second or less
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
@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
circle back around to it soon
I see I just overwrite it .. I think deleting is good so no space is taken
you might have to implement a __call__ method to call the your class object
anyways imma go
yeah that's already what i'm doing right?
?
are there any warnings or errors from return self(*cache[bob])
haven't tested yet, so much code to go through before then
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
blacken doesn't say anything about it when i auto black my code, ide isn't much help apart from that
if it could be anything, typehint could be Dict[Any, Any]
hmmm
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
okay thanks dude, night
np
that's good but if you get the high end of popularity itll be harder scaling
1 million images at 5mb = 5 tb of data
yea u r right
I will try to figure that out once I fix this time thing ;-;
just os.remove
oo only one line
so basically once the message with image is sent
u delete the image hmm
well i upload to amazon server and save the url
oh wait I forgot to tell something .. this is global leaderboard image so its only one image saved with same name
thats why I over write it
in ur case ur saving images with different names , right?
hmm thatll be a problem
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
ah so its best to store image with uid and delete it later , right?
pil kinda saves the image like slow internet where it fills from the top
;-;
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?
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
im gonna need a lil more
nicee I feel pretty noob at pil so It will be a great help for me XD
I'd prefer doing it in the init dunder

so I made the resolution but all of the sudden my code is stuck on one line ;-;
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
hmm can you have alpha values in colour like that or is it just rgb
what's the error code
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
so you're just not seeing the text on the image?
nope I mean bot keeps thinking
no image is generated
this is the only output .. dont mind those print values
that's weird, i would assume an infinite loop somewhere if it's just not doing anything
or you messed up a value somewhere by 10x and it's trying to make a huge image
hmmmm
Could you show more of your code
my text gen code for comparison
The way you define image ,or the loop if any
Ik I should cuz I am asking for help but I dont really feel like ;-; .. sorry I will go and try figure out stuff .. thx
thx for the example
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
o
although text can't be that hard to draw
I reverted back to 4000x2000 code to see where I made the wrong change .. hope I find the bug xd
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]
I figured the error and switched to 800x400 but time still takes like 4 secs
so should I assume its cuz I am drawing lot of stuff
I think I will have to share the code ;-;
@spring verge it's probably taking a while and is blocking, how long are you letting it run that single line of code
Any idea on how to solve my issue?
do a timers between operations and see whats being slow
where's your convert function, inside another command or...?
yea sure.. brb
how do i fill in values without resorting to f strings here
for the ? regarding a column name
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?
yeah works the same here except when you try to replace a column name value
sqlite3
o
what's id?
in asyncpg u cant actually put table name with parameter values
trying to do this
so probably sqllite3 has similar issue ?
if it's a user ID then you can use f strings I believe
so I have to always use f string for table names (but dont know about column names)
eh f strings work and it's not a user input so should be fine
yeah, there must be another way though
you'd think so
there is no parameterization way for "table name" in asyncpg
will sql injection problem get prevented?
basically recommending to do it my way here
In a def
cuz we dont use f string because of the sql injection problem
Just use the first way
Not the second one
ye I already am
No... They are the main cause of sql injections
she is not using for values
table names or column names cant be replaced by parameterization
well they're saying here they never bothered implementing placeholders for column names because there's no safety risk
She?
And used in multiple commands to convert time
he
he*
Ah okay
so I think its best to use mix of f string and parameters
parameters for values
For?
and f string for table/column names
π³
Hunter can you tell me how I fix my convert issue?
Like, mind giving me an example. I ain't following the convo
What's the issue? I just came here bruv
lol same
f'SELECT * FROM {table} WHERE user_id = $1' , ctx.author.id
so how will u replace table name in asyncpg when u cant put parameter value for it
thats not a place holder?
only me
Ah then it's fine
$1 is a place holder?
since when?
what
wasnt place holders % ?
I have been using it for decades
only 2 symbols
i've been using ? for placeholders lol
No smh
yeah same
ποΈ ποΈ
That's a way for string formatting
what the %
The % sign
ye
Yea...
i thought it was a placeholder lol
It's used for string formatting, just like f strings or format method
yea I understand that if table can be set by anyone else then its a problem but sometimes u gotta use variable
yeah ik
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
Any luck of solving my issue?
ok so I found out that.. 3-4 seconds are taken in arranging loop data
so there is no problem with pil or easypil ;-;
like pil work starts after arranging loop data
lemme share the code
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
read the error
thxs
youve been ratelimited
You are being blocked from accessing the API temporarily due to exceeding the rate limits frequently.
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)
how many users are you fetching?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
oh 5?
so basically I have made different lists
and appending the user data to it
and access it when doing image stuff with pil
guys this is kinda ot ngl
ot means
off topic
This is my code, it shouldn't be rate limiting but it is. https://pastebin.com/rXuywaUQ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is off topic or the rate limit issue ..?
kinda confused here ;-;
not mine
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
yeah nice nuke bot
only top 5
i wonder why youre getting ratelimited
this
isnt that img manipulation?
but isnt the code related to discord bots?
5 shouldn't be that much of a problem
technically that code doesnt even have any manipulatuion except one line of code
its just getting user data
so its like 50-50 idk
this is against tos.
we wont help with shit that goes against tos
not really its not really about dpy
I mean eh imo it is kinda related but that doesnt mean u r wrong
the elipse circle drawing thing is around pfp right?
ye
try not doing that and see what happens, curious
i mean that code you sent is more about img manipulation no?
just keep square images
it takes like 0.04 s
before that and after that code
so shouldnt be a problem..ig
how high is your ping?
but its still related to storing data in lists etc..
if it's taking you 500ms to fetch each user that might be the problem
wait ping of me , right/
@echo wasp is your issue fixed
try ping command for discord
Im guessing you have the convert function inside a command so it doesn't work outside other commands
Trying a different server at the moment and I think I know what is wrong
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
Oh Lemme try time on it and see how much time it takes
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?
Can't see anything wrong with it other than the fact that it Doesn't follow Pep8
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,
@final iron can help u more on this topic (:
?
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
what's your ping
bot.latency / client.latency and print
fetching 5 users should be pretty fast
thats not ping
thats the latency on a ack heartbeat
should give some indication on the connection to discord servers tho
It's heartbeat_latency.
yup
so you know whats the estimated latency on a ack heartbeat
why?
Nah I mean, it's not bot.latency, it's bot.heartbeat_latency
For them
doesnt bot.latency return the latency on a ack heartbeat
!d discord.ext.commands.Bot.latency
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.
yup
Eh they ain't using discord.py
ah
I am using hikari lightbulb :)
Oke
If it's over 0.05 stuff like sending images would be slow
Depending upon the size of image
that's 300ms
yep in 0.1ms max
800x400 resolution
I mean, in kbs/mbs
yep 0.1ms
send it through respond()?
the most time is taken before saving btw
It's because you run a loop which may be taking a long time
like 3 seconds goes to other stuff before beginning image manipulation
hmm but u said latency is 0.3
which is not good?
Thats just like your internet connection, nothing to do with your code other than sending/recieve data
!d discord.Guild.edit
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.
yes so 0.3s goes where? receiving the command and sending the message? or I am misunderstanding something
wouldn't 300ms be a lot if they're looping 5 times
fetching 5 users would be at least 1.5 seconds
so half of time is going there?
Yeah, Discord doesn't allow that. You could transfer the ownership to the bot, maybe, or have your bot create a new guild
hold on ill check my ping to compare
mines 0.1
and i consider my connection to not be too fast
Hmm but it takes u like only 0.5s to get image
They fetch users?
Yep from PostgreSQL
yeah, i mean does your code actually need to fetch users
there must be a way around that
Yea Imma look for that
you could save profile urls to a database whenever someone interacts with your bot if you had to
profile urls?
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
avatar url
but what if person changes their avatar
wait u mean
I should store their name etc everything
everytime they invoke a command]
does hikari have getch?
it's only for their highscore, it can be a little out of date
!d disnake.ext.commands.Bot.getch_user
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.
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
pretty handy in disnake
for the people using the bot enough to get on the leaderboard i imagine they're interacting with the bot often anyway
hmm true
No, it's the opposite. Imagine inviting a bot only to get your server deleted, and being sent scams
Imagine how fun it would be-
what do i need to supply to thease args? (self, ctx, mins : int, * , prize: str)
it is
its an alias
!d disnake.Client.get_or_fetch_user
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.
can someone tellme what args i need to supply the command? for it to work?
oh ok
yup
it was my idea to name it getch idk. Who knows which idiot came up with that name Β―_(γ)_/Β―
you have nothing to do with self and ctx, all you input is the command prefix and name and the amount and the prize
!giveaway 60 fake nitro
ok, how to remotely cooldown a ppl πΏ
!d discord.ext.commands.dynamic_cooldown ?
@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.
time and prize*
Lmao
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
get and fetch separate
then show the role names, not the whole objects lol
[role.name for role in guild.roles]
also ctx.message.guild is unnecessary just do ctx.guild same with .author
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)
isnt php that has that operator?
JS also does
isnt that if equal
=== in js exists because == does type conversion
'1' == 1;
// This is true
'1' === 1;
// This is false
So the @unkempt canyon and other bots are moving to disnake for the time being π
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.
not really, discord.py is not mantained anymore for a long time, so it is starting to be outdated. People are making new fork based on discord.py and there are plenty of them. We just choose the fork that we prefer, disnake if one of the most used
you can use Minecraft server API .-.
I don't know how to use APIs 
And it's almost done this is the only one problem with it
i don't understand your problem lol
Bro... Ik. I just told what they announced in #dev-announcements
Lol didn't read it yet
Hello. Has someone seen a good tutorial for transcripts on a Website for modmails? Feel free to ping me
because you have no variables called guild
!indent
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
and why the heck is client coloured like a class
Isn't that the default color iirc?
Like the default color of a class object
it is but how would you even make an event from a class that isnt even subclassed-
class Bot(commands.Bot):
def __init__(self, Bot):
return Bot
@Bot.event
is invalid
any in-code example?
Yea it is... also u should do return self lol
Iirc there's an example in the docs
πΏ nope
yeah I deliberately wrote it
Also that will raise an error anyways. U can't return anything in the init
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")
π€¨
U r missing a comma
oh
After intents=intents
yea i see it now π
||i mean like when i type a comand, some other comands will also get a cooldown||
U using cogs?
smh you got the idea
i.....dk?
U just want to show that u can't use that deco on the class itself, no?
no
yeah
Lol u gotta add the deco manually to every command
Cool π
can explain how dis work πΏ
also, why arent giphy/tenor links loading in embeds ;-;
wait really?
What's the url u setting?
you need to go to the site, and copy the real url from there
Yes
yeah I did that
the one you send from discord wont work
mind showing the gif?
I went to the official gihpy websitee
sure
no
This just checks for the message author and return something depending on the author
Stop it
why do i see js everywhere π
discord.gg/djs is waiting for u
https://giphy.com/gifs/PHZ7v9tfQu0o0 idk this URL is what u using?
https://media2.giphy.com/media/PHZ7v9tfQu0o0/giphy.gif
O
how do I get these though? and yeah it did load
@discord.ext.commands.dynamic_cooldown(cooldown=60.0, type=BucketType.default)
@bot.command()
async def test(ctx):
await ctx.send("test")```
is dat works like dis
Bro
copy link ofc πΏ
huh
asdf, wait why mp4
https/media2.giphy.com/media/PHZ7v9tfQu0o0/giphy.mp4 this is the url you have, change the .mp4 to .gif @slate swan
πΏ ok
sorry for the ping m8 πββοΈ
no prob, me ping friendly
oh thankee, no wait
waht
right click copy image url
what the url you get?
or should I use the codes and append them behind the media route?
just open it in a browser tab
oh lmao
you will get the link i sent
@slate swan would like to explain you about dynamic cooldowns
Oki thanks you
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") ```
πΏ still.... not nundesratdn
read it
understand
or ill write a novel again
API says this πΏ
yo
btw I am using getch now (get and fetch together)
and still taking 2 secs for 5 user ids
idk how do I resolve this aaa
ah , then you may mention the bucket below
everything else remains same
???
the cooldown variable there is the bypass_for_owner function
do you cache all those data anywhere?
ooooh i see
wait, cant i just cooldown=(second)?
whats the point of doing that, if you want it you may just use a normal cooldown...
well
basically i wana add chop command, but when i use that command, 2 other commands are also cooldowned
!d discord.ext.Command.update
!d discord.ext.commands.Command.update
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.
takes a cooldown kwarg
how to use?
I think
I just realized I dont know how to cache data
how do you use getch then?
.
how to add options in slash commands (disnake)
see the old.py and param.py
wait lemme check
they are parameters, I want options for parameters
thats how the options work...
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):```
string, channel and number will be options there
I want a menu like this
That's an autocomplete , not options
tell me about it please
u cant have more than 25 options btw
fine
just telling cuz there are lots of pokemon
I'm not copying that bot, it was an example
pokemon: str = commands.Param(choices=[])
And you achieve same thing 
^^^
I checked and I have intents
what I dont get is if I check my ping normally
its 26ms but when I print the latency in code then its 300ms
oh and make sure the get_user takes an int type
Cache doesn't depend on your latency.
ohh thanks
yea user_id by default is int
btw I will be hosting my bot on galaxygate soon
so should I really worry about the code ?
Idk if I really need get etc
π€¨
how can I respond with different messages when different option is selected?
Nah , any host with python 3.8.5+ would let hikari work
oh I meant the latency issues with code XD
Nono it would be good like 50-100ms
For my replit it's 32 ms and works decent
so I can expect bot to reply within a second 0-0 instead of in 3-4 secs
Before someone gets triggered it's a basic bot with an eval command, that's all
if var_name == "choice name":
. . . Do stuff
Yea
me paying just 1,5$ for host and have a 20-30ms latency
me not paying for a host and getting 35ms
howw
:)
my bot gets 300ms and when I test on google I get 26ms
I still dont understand the difference
doesn't matter, i get 6 ms normally and 350 ms when I run the bot from my pc
u just now said 35ms without paying for host 0-0
local ping that you measure from speed test is different from the ping you get somewhere else
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
ooo
oooo
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
yea true I thought bot takes fastest server or something lmao
no
They take discord servers .-.
now I get it me dumb
you connect to discord API
ye Idk why I expected it to connect to same server like normally
anyways thx my doubt got cleared :)
max I've reached is 1200 ms when running my bot locally lmao
What site is this?
i never reached latency those high locally D_D
how can i get a message object by id
(i would use it to update the bot's message)
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}")```
i think that you have to fetch it by the messages in a channel because the get_message method searches from bot cache
aight
There's no get_message tho
yes, the get_message method uses bot cache, you need to get the channel of the message and then fetch the message from the channel
!d discord.TextChannel.fetch_message
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.
!d disnake.ext.commands.Bot.get_message
get_message(id)```
Gets the message with the given ID from the botβs message cache.
!d discord.abc.Messageable.fetch_message
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.
what were you sayin?
i see there are differnt ways of doing this
Isn't that specific in Disnake?
use discord docs here
dunno if other forks doesn't have it
No they don't
since most people either use dpy or other forks
i use disnake either way
Umm I forgot the name ;-; rn on phone
this chanel is rilevant to discord.py and his forks
Ah you're cool then
use what blacktvriser showed them
alr thanks guys!!
Btw hikari and disnake are currently most popular?
nope he can't
get_message method search the id from the bot chace
yes, I'm saying when giving support, use discord docs
? why do i need to use that?
As a non fork yes hikari is popular
Disnake is efficient and recommend here
Pycord is advertised and is more popular
i could get message and message.edit
you can use get_message if the message is saved in the bot cache
oh
bot cache is deleted whenever you turn the bot off
that might be a issue
yeah just fetch the message from messageable if you don't have the channel object
else, fetch it from the channel
I personally like hikari cuz u can use command handler or component handler with it .. idk about disnake ;-;
yup, you have to use the fetch method from messageable or a channel object
.
i'll fetch it then
almost every forks has handlers
why trying to complicate things so much
my code is a mess, i dont have a command handler and about 600 lines lmfao
Oh I see .. I thought it was only a dpy thing
I'm a hikari user as well ( my nickname already suggests it) , Disnake is a good maintained fork :p
Hikari gives an option to use 3+ command handlers....
!pip hikari-lightbulb
^
!pip hikari-tanjun
And one more but IDR it
well, in disnake you can do some workaround and it will work anyway .-.
btw never needed to use them
Ye ofcourse , but hikari-lightbulb offers Making slash commands and normal commands within a single function π, saves time+extra lines of code
Damn 2.0 is op
I like how they added that decorator feature
i use only slash commands lol
Just use implementation and bam u r done
And it makes you a slash help command by subclassing the Help class , which I don't think any fork does
yes you can do it with disnake .-.
oh? Docs pls
Btw I still have some confusion about cache ;-;.. so like get_user always returns None for me. Now when will it be successful? Like how to know when bot will store user in cache
btw this could be usefull but you can have issues with that, for example if you have a command which takes two strings as parameter of undefined length, using a normal command you need to use a separator for the two strings
with slash commands you just check which one of the two option are passed in the parameter
Lightbulb doesn't work on function arguments
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 ;-;
@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
Your bot cache is deleted everytime it runs off, data are stored when some events are triggered
message are stored in the cache when they are sent and the bot can see them
Ok let's go in detail.. now my intents are enabled
ok, if those options are two string of undefined length, how you pass them in a normal command?
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?
yes
So for command invocation event let's say I invoked a command
@placid skiff
The event runs as well.. but still get_user returns None
and I didn't turn off the bot as well
Ok, i read it how it works, but you need that two strings, and they are not parsing
get_user doesn't search in the cache
Eh?
Inherited from Cache.get_user
Or I misunderstood u
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
@bot.command
@option("a", "arg a")
@option("b", "arg b")
@command("test", "a test command")
@implements(SlashCommand, PrefixCommand)
async def test(ctx: Context):
await ctx.respond(ctx.options.a+ctx.options.b)
Β―_(γ)_/Β―
how do you mention option descriptions in disnake?
without that old options arg in the deco
Damn 1v1 going intense
Btw whenever it's done.. tell me.. I still need to discuss about get_user lol
ok how the prefix command will tell which options is pass, they are both two strings, slash command will separate like this: a: str1 b: str2
the prefix command? he can't lol, for a prefix command only the "a" option will be passed
String parsing go brrr
you know how decorators work right? bottom to top,
so first the b will be taken as the first argument
and then a as the second...
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
ok, test that command and pass something like this a="i like" b="coding with other people"
no, the prefix command will get only the two first string in the arguments
first thing first , you cant do that in a normal command even with disnake.
no, the prefix command will get only the first two strings in the arguments
so you mean , .test a b cde e f will ignore cde e f?
@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.
For what i read the consume_rest will just not parse the other string
consume rest does the same work as *
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")
What you didn't get of "undefined length"? π π
not working help
You are... Tryin to create a user class from a message Id?....
userid
lol
i nmed it msg
That's not how converter works lol
just
You have to use fetch or get method
how
it is not in mutuls
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
It will work in all guild...
It will work anyway π π
ok
giveme the ixed version o my code
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?
user: discord.User = client.get_user(your_id)
#your event here
The id must be an int, not a string
ok
@slate swan we will continue this discussion π
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")
something went wrong with the get method
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")
check this
prob not cached yet
nah get_user doesn't need cache i think
wott should i do
wdym by undefined length? a normal command will take a single word , you can have as many you want for the slash one
the library parses it that way...
hey
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")
pls help
with this
presume that a user will use that command and he will send a="abcd" b="def", another user use the command again but send a="abc" b="defg"
this, it can get a fixed length or *
but you don't know the length of the string untill the string is sent
;
on_ready event doesn't take any argument
@option("b", modifier=CONSUME_REST)
@option("a")
Is same as ```py
async def function(ctx, a, *, b):
wott to do then
ID should be a int, not string
ok, but a is fixed (the first string sent) and b takes the rest of the string, what that command should look like with a prefix command is this:
@command(description="separate strings with \";\"")
async def test(ctx: Context, *a: str):
str_list = a.split(";")
await ctx.send(f"{str_list.index(string)+1 for string in str_list}: {string for string in str_list}")
get it now?
... remove the quotes or int()
no? noone takes multiple arguments like that....
or do you mean splitting with ;?
it is an example, i have a command in my bot that has to take different string of unfixed length
with slash command is simple because i don't need to separate them with a separator
@client.event
async def on_ready():
msg = '750015265135263835'
user = client.get_user(int(msg))
print("I'm in")
print(client.user)
await user.send("hy success yeh")
?
if I used a prefix command i had to separate all those strings
in that case ```py
@option("your_string", modifier=CONSUME_REST)
@implements(SlashCommand,PrefixCommand)
async def command(ctx):
str_list = ctx.options.your_string.split(";")
await ctx.respond(f"{str_list.index(string)+1 for string in str_list}: {string for string in str_list}")
Won't work cz the cache isn't ready at that time
in the end, those two commands became a totally different command because one just use the options of the slash command, the prefix command has to separate each string with a separator
ok any other event?
Use tasks.loop and set the count to 1
docs
!d discord.ext.tasks.loop
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").
a is a tuple
ok lemme try
;
@tasks.loop(seconds=1,loop= await user.send("hy success yeh") )
?? this??
no, just the time seconds=1
wott bout tsk?
then inside your function, do what you were doing in on_ready
@tasks.loop(seconds=1)
async def send_task():
#code here```
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)
no tasks.loop is a decorator
how to send tsk?
Remove @client.event and on_ready
msg = "750015265135263835"
user = client.get_user(int(msg))
@tasks.loop(seconds=1)
async def send_task():
print("I'm in")
print(client.user)
await user.send("hy success yeh")
this?
.
yes and now start the task
send_task.start()
ok
i think its called, not sure
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
Not seconds but count lmao
count = 1?
what?
await bot.wait_until_ready()
Add this at the top of the function
ok
He wants to send a message to the user only once
idk i haven't really used tasks lmao, but yes makes sense. it will stop after doing it once right?
Yes
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ξΊ§
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.
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()
Bro
.. you are trying to get the user before the cache is ready, put it under the wait_until_ready
Get the user inside the function
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")
bro how much do you know about python?
Do you have member intents?
;
no lol w8
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
If you knew you should know the problem with your code .-.
........
this is supposed to be a place where people can ask for help, whatβs wrong with them asking for help?
we are helpin' him for half an hour lol
You need member intents to use get_user
ok
ok
Then don't help him anymore. But don't ask him to stop asking questions.
i didn't ask him to stop askin lol
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))```
Not directly but you are being rude.
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'
random.choice
@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()
too few args thing?
!e ```py
import random
for x in range(4):
print(random.choice(["yes", "no"]))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
001 | no
002 | no
003 | yes
004 | no
yea that should work
your .format()
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'
ye ik πΏ that's why i ask, how to make random death phrases
still
actually, choose 1, f-string or .format(), not both
oh and you're missing value kwarg
add_field(name=..., value=...)
r u kidding πΏ where ctx? where async thing?
ik :V just skip
If this code is fully valid i recommend doing this ```py
d.add_field(name=f":crossed_swords: {random.choice(deathPhrases)}", value="** **")
; bruh no cmd
what
Does the id belong to a user
And is that user in any servers the bot is in
no mutul o bot lol
Then it won't work
i ws trying to do tht only dm with out mutuls
use fetch_user

ok
πΏ how to shut this thing up
works even when the user doesn't have mutual guilds with the bot
Use getch if you're using disnake.
da hec is mutuls
client.fetch_user(int(msg)) ?
ye, but they still won't be able to dm the user
what does it say
yea that's the problem
What thing? You mean the yellow background?
too few args for format ofc πΏ
dont use .format()
no, too few args πΏ
Could you print out the deathPhrases?
πΏ no other idea what i should use
show your current code
deathPhrases=["{} hurting {}", "{} poking {}"]
da hec, all code?
πΏ ok
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
oh you're doing that
then use the .format() like random.choice(deathPhrases).format(hurter, hurted)
Still, no.
{0} hurting {0} also string formatting uses 0 if i'm not mistaken
oh it doesn't matter, my bad
f-strings exist
deathPhrases=["{} hurting {}", "{} poking {}"] for this case it won't work
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
cause you're formatting a string which exist already
What's stopping you from using single quotation marks
im literally so lost
I'm assuming you are coding in OOP?
Is it a bot variable?
Don't think a button is tied to his bot var.
no like, you can do this
a = f"{something} hurting {something2}"
but not this
a = "{} hurting {}"
# what should I do now?
``` the best choice is to use `.format()`
```py
a = "{} hurting {}"
a = a.format(something, something2)
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
Right, although you could just do an f-string on a where a is just " hurting "
I'd pick the f-string since it is more flexible to edit. The .format will always force you to have x before y
Wrong
currently not using oop
They are both just as flexible, but f-strings are shorter to write
No? In a list like his .format will be difficult to re-arrange.
What do you mean?
Imagine he wants something2 before something because of a different death sentence.
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)
a = ["$author hurting $target"]
@bot.command()
async def foo(ctx, user):
await ctx.send(a[0].replace("$author", ctx.author).replace("$target" , user))``` πββοΈ
Also a valid option, anything better than .format
π
And i told you that this isn't flexible.
What if you want the user first and not ctx.author?
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
Bro
the only choice is to use .format()
was just a "not really" thing lol
Just give me one. fucking. reason. why I shouldn't hate u
fixed π
you dont need one
Passing context as: ctx: commands.Context is really old right?
no?

