#discord-bots
1 messages · Page 852 of 1
Okay!
I smell cringe .format
.replace >>>>
using typo makes your code more readable too so why shouldn't do it
🥸
can someone confirm the rate limit for fetch_user?
I confirmed it's an api call
Omg hi zeffo!!!!
don't think there is a fixed rate-limit, larger bots are given more relaxed limits
hi novA!!
how to make discord bot zefo
Oh well
just copy from swas.py 🙄
oh but how large is the requirement? is it unknown?
That's not documented afaik
swastika??!!?
yeah he is best coder
You can calculate it.
^
Oh ok
All bots can make up to 50 requests per second to our API. This is independent of any individual rate limit on a route. If your bot gets big enough, based on its functionality, it may be impossible to stay below 50 requests per second during normal operations.
This is independent of any individual rate limit on a route
nova have you used Rin
ohh so 50 reqs per second
that's just the global rate. The one for the endpoint in question may be stricter
Yes, I even have her ~800 photos
I thought global rate limit applies on that endpoint ..wait lemme re - read it
pls weekly
pls weekly
discord api docs sucks, so don't expect much
yea I still didnt get what rate limit is applied on it ;-;
Imma assume my bot to work for now ig
!sql-fstring
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
that's what i do...?
it is, I'm just saying to another person
who
Roie (350619697231691776)
oh ok
but anyways, is your problem solved?
What will I have to add so the bot responds when a human user clicks a reaction
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
or that
?
i see
sus but okay!
wait_for wait's for the user to click the reaction, while on_reaction_add listens to reaction add events
thanks @visual island !
thanks @vocal snow
How and why do i see these sentences together
💀
smh ok
example of?
nothing ignore it
👍🏼
?
This is an example from rapptz
ill see to it
name = message.guild.name
base.execute('CREATE TABLE IF NOT EXISTS {}(userid INT, count INT)'.format(name))
base.commit()
warning = cur.execute('SELECT * FROM {} WHERE userid == ?'.format(name),(message.author.id,)).fetchone()
if warning == None:
cur.execute('INSERT INTO {} VALUES(?, ?)'.format(name),(message.author.id,1))
base.commit()
await ctx.send(f"{message.author.mention}, 1 предупреждение.")
elif warning[1] == 1:
cur.execute('UPDATE {} SET count == ? WHERE userid == ?'.format(name),(2,message.author.id))
base.commit()
await ctx.send(f"{message.author.mention}, 2 предупреждение.")
elif warning[1] == 2:
cur.execute('UPDATE {} SET count == ? WHERE userid == ?'.format(name),(3,message.author.id))
base.commit()
await ctx.send(f"{message.author.mention}, 3 предупреждение.")
sqlite3.OperationalError: near "Greatest": syntax error
Help me
whats the problem showing up in the console?
🤔
What is Greatest? I don’t see it anywhere in the code
use 1 equal sign
sql uses = for comparison and assignment, yeah
@bot.event
async def on_ready():
global url
print('landing success gg bruh')
file_extension=['jpg', 'jpeg', 'png']
reddit = asyncpraw.Reddit(
client_id="",
client_secret="",
user_agent="",
)
subreddit = await reddit.subreddit("test")
full_list =subreddit.hot(limit=1000)
url = []
async for submission in full_list:
if submission.url.split('.')[-1].lower() in file_extension:
url.append(submission.url)
@bot.slash_command()
async def himg(ctx):
global url
url = []
randurl = random.choice(url)
embed = discord.Embed(title="test?", color=0xcf24ff)
embed.set_footer(text='test')
embed = embed.set_image(url=f'{randurl}')
print(randurl)
await ctx.respond(f'{ctx.author.mention}', embed=embed)
i am trying to send a random image from a subreddit using their official api its just i am getting error of
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: IndexError: list index out of range
i am using pycord
you set your url to an empty list
what do you want from an empty list
and don't use on_ready like that
and use bot variables
Hello, i'm using discord_slash and discord.py
I made a slash command with a required option with 2 choices
I want to make different replies based on the option's choice the user gives
how can i do it?
Is there a easy way to convert Slash commands to Normal commands, which can be used simultaneously?
The problem is that disnake often want's to upsert the slash commands to discord, which makes them not usable.
What do you mean upsert
Starts to register them again
The answer to your question is no
You would have to make 2 seperate commands
1 slash and 1 prefix
Ugh
use hikari if you want to make them in one
It's really annoying, I accidentally copied the wrong bot token and ran it inside the other file, which deleted all slash commands from cloud
🗿
Wow
shit happens
for complex cmds & big bots it's a pain to convert them to slash. took me ages to get it all done
not a big deal though
☝️
I mean, my bot literally had 227 commands, and All of my code was lost when I factory reset my laptop, what can be more annoying
oof
I didnt know github existed that time, I was really smoll
I was like 12
at that time
and rip my bot
Friend backups the code on USB stick, every now and then
who does that :kek:

Just taking picture of the source code is the chad move
just making a private repo is more
anyways, lets keep it on-topic, before someone warns us
I also do that when a major change in th code happens
Like how I migrated to disnake
I have like 2-3 archives with early versions of the bot
uhhh oof
yep
and so u don't fuck up other collaborator's code
I simply push broken code to github
mhmm
I often do that too
Hasn’t most people done that?
probably
If you haven’t pushed broken shit before. You're simply lying to yourself.
uhh I'm just too lazy to find any errors, so I upload it to github and send it to 20 of my friends and they fix it for me
lmao
kek
lmfao
just write tests 🦅
people don't test before pushing it to master?
The happiness when a big embed works without any KeyError or typos
lmao
I mean, I do but when I'm sick of not finding it, I just do my "good" practices
Here comes the mod to warn me about me about that word. 
Please avoid using ableist language.
rip
My apologies.
dawwwwwn, give me a warning too
I used the r word and quickly changed it to special
oof ok
They probably caught it before I changed it.
You know... message logs are a thing 👀

Just make a wrapper for the API then 👀
And publicize it as well so I can use it.
Easiest way if u don't care about type checker and @final iron screaming at you:
class Something:
def __init__(self, data: dict):
for key in data:
setattr(self, key, data[key])
I'm too lazy anyways, disnake works fine for my purposes
🤨
Oh btw
Akeno completely follows pep8 and there are no type errors
Wrong server/channel?
Stop cap.
Okimii following PEP8?
Lmaoo facts
It was all me 😔
100% you blacked the code and just said it was PEP8
Bros
I haven't done that in a while
!ot exists for talks related to twitter wrapper
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
man.
No blaming, imma just head out
i made the function to write an image url in the list
and the reason i use on_ready because if i try to use the api keys in the command it takes 8 seconds for it to run so i used the api keys in the ready so it can run first
akeno/tweet.py lines 4 to 7
__all__(
"Tweet",
)```
check your command again
url = []
randurl = random.choice(url)
there's no need to set anything to None when defining it anyways
that's not a python thing
so the url list is empty?
because when i used print(url) it printed a lot of images link in a list format
ohh
give api
Not me
Okimii is the one working on beta
Wait does that even break pep8?
that doesn't even work
__all__ = ( "Tweet", )
and what's the point of formatting a single element tuple like that
To support wildcard imports
it can be a list or tuple of names
Nah I meant why format it like py ( "Tuple", )
c# moment
Oh lol
When it's a single element
it doesn't even implement twitter's streaming api okimii is such a bozo
@slate swan git gud
😂
hi, Im making a timer command but i want the people who click on the reaction get pinged when the timer is over
iterate through the members that added the reaction and send a message to them
i want something like timerbots
like whoever like reacts should get the ping at the same channel
whenever a user adds the react on that timer you have to add the member to a list
when the timer goes off you have to iterate through the list and then send a message to them
after that clear the list
is it possible to my discord bot's slash commands pop out as the wise/ in line we want
e.g.
when a user presses / and select my bot's menu first it will show the main help commands and below the other commands
i am using pycord
i am a bit of a new to coding thats why
to create bots you need a good knowledge of python
you know about async?
yeah
OOP?
nah
OOP is essential xD
then go and read some docs
not in d.py
yes ig
d.py is object oriented
its a must for timer bots cuz gotta save stuff
and python is object oriented
could you explain what oop is
in fact .-.
full form?
object oriented programming
#python-discussion please
ok
Shhhhh
first learn some docs and dont think that they will not help in coding cuz
"Knowledge if not useful when you are learning it, its useful when you use it"
Ok and your point is? D.py requires an intermediate amount of oop knowledge. Cogs are oop based, Component Views are oop based. There’s just a lot of inheritance.
oop is like variables
If you're wanting to subclass either one of the Bot/AutoShardedBot classes you need to know oop to a minor scale atleast.
i used to use java but no expert
not only that, everytime you use something you are calling a method or using a parameter of your istance, whatever that istance is, so knowing oop make simple readin the doc too
Uh. no
hmm
not exactly .-.
lol
imagine arguing about things you dont know
ik
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
is there a maximum of how many bots i can make in one discord account?
my life
i dont think so
dont think so, but dont overload your stuffs
also you can run only one token for execution i think xD
no
can you run more tokens?
yeps
each bot has a different token
but not a good practice since uhh
lol
if one of them gets rate limited, rip all the others
oops forgot about the rate limit
i mean I saw a Reddit post a little bit ago about some guy saying he couldn’t make more than 10 applications on the "My Applications" page. Coinciding with you can probably only have 10 bots per account
thanks
just simply try making them
and see how many you can
who even needs 10 bots anyways
like fuck
its the same bot but over and over
delete the previous versions
i mean like it would bypass the verification thing for 100 server
class Dropdown(disnake.ui.Select):
def __init__(self):
self.msg = None
options = #options
super().__init__(
placeholder="Help Menu",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: disnake.MessageInteraction):
#if statemnet
await self.msg.edit(...)
raises NoneType has no attribute edit
(Yes, I put view.msg as a send(..) in the command)
that is seriously a bad practice
msg is None dude, you initiated it that way
but in the command I did
view = Dropdown()
view.msg = await ctx.semd(..)
(Yes, I put view.msg as a send(..) in the command)
"semd" sure
is it possible to make slash commands pop according the line/wise we want like
when user press / and selects my bot's menu it will show the main help commands first and than the other command
i am using pycord
typo here, not in the code
I dont think so, but, I guess, every single human being was given the common sense of knowing that a help command exists
I know but its discord
discord has kids
kids are stupid
lets take your example and solve this problem
shame on you for this
how old are you
bruh
guys listen
I am the only one who has a channel just for code snippets where you post random pieces of code thinking that probably it could be useful for later in your bot? 
Was it black?
It might have been black
No not at all
It's because okimii sketched to sublime
!d disnake.Message.embeds
A list of embeds the message has.
btw, can you send a list of embeds like await ctx.send(embed=[embed1, embed2, embed69, embed420])
and if there are no embeds what does it return?
why don't you just try and see
yea Messageable.send() has the embeds kwarg.
I got these error while running my bot. Can someone help?
first
are you running a spammer of any sort
because you're getting 429's like hell
and spammers usually cause crap like that
constantly sending message, deleting bunches of channels, creating a lot of channels, roles, like that
Ooo
send all the code (not the token)
I was trying to make a modmail that only send the message to my dms, and when i run it, the bot spam my dm
yeah you might've created an infinite loop
alr, send the code over
tl;dr never use replit
I didn't have PC/laptop so I code on mobile and use replit
yes very much
I do
I think i didn't use this module anymore
@hoary cargo , remind me again, what statuses are against discord TOS?
i know mobile is, but are there any others?
Do i have to delete this?
best to
add await client.process_commands(message) at the end of your on_message listener, and turn that listner into an event.
listeners are only for cogs
ooo
I use client.listen() to one of the event message, to check the specified words to delete
Cz if i use .event, the client.command won't work
Someone suggest me to do so
read my messages above
@quaint epoch Like this?
I think streaming
Listeners aren't only for cogs 🤔
not sure
yeah
This would make commands only work in DMs
btw, you should rename client to bot
why though
conventional
Wait, i still get blocked
blocked by who?
Your processing in the DMs only
Not sure why you even changed back to event when listen() works just fine lmao
you getting 429 errors?
Ya
sorry we can't help
this will temporarily solve your problem
go to replit shell
and type kill 1
Oh well
and then restart the bot
Rip
or close replit
that wont work
Or never use replit ever again
i have tried that before
yeah that
Wdym restart


he is coding on mobile man
run your bot after typing kill 1
Soooo? pydroid ftw!
thats what i meant by restart
w3 schools still works
Where is the shell
show screenshot
Oh wait
If he got a CC, then just get oracle free VPS
I didn't get blocked anymore smh
nice
I mean you shouldn’t be hosting on replit either
also 
Thanks for helping guys
oracle?
Replit is an online ide not a a hosting service
what caused the ratelimit in the first place
For instance, Raven here also got it and now is hosting his bot on it without any downtime
Being on replit and shared ips
I making a modmail event to send the mod message through my dms
Mhm
NO downtime at all
which command specifically caused it
Yea... that's what I said
And smh the bot spamming the text on my dms, so I delete it
is it 24/7 hosting? the discord bot
just verifying
thats why you get 429s bro
your bot spams
@client.listen()
async def on_message(message):
if str(message.channel.type) == "private":
bot_owner = client.get_user(550588846706786305)
await bot_owner.send("[" + message.author.display_name + "] " + message.content)
Ooo
so, it just happens when a message comes on?
Just return if the message.author.id is the same as the bot's ID
So then the bot would no longer send messages that trigger your on_message
i see what it is
add if message.author.bot: return at the top
Indeed
or just
if not message.author.bot:
#code here
I see
any limitations? like a certain amount of hours per month or anything like that
(forgets an if statement) (is promptly IP banned from using the API)
was wondering if this is correct method of using get+fetch?
@brittle axle do you know something about 400 Bad Request?
i dont know about that man
i have only encountered 429
getch works better
Ooo
you mean fetch
getch
using get+fetch is allways bad, you should use only one of them
what is that
!d discord.Client.getch_user
there is no getch in hikari lib
LOL
oh you're using hikari nvm i thought disnake
but I was told to use get+fetch cuz it reduces api calls
Nope. Just don't mine crypto on it
Idk how is it bad
You can just use an or statement, E.g ```py
get(....) or fetch(...)
but who tf uses wrappers anyway, the chad way is to use aiohttp to pull and get requests yourself
oh ok
That way, if your in-memory lookup returns None it will call the fetch
Bruh hahahahah get_user use api calls as well
🤔 No?
No? it takes data from cache
Lmao
Idk which lib u use but in hikari it takes data from cache
So sure?
Yea, that's from the cache
https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/state.py#L347-L349 guess this is an API call now lmao
discord/state.py lines 347 to 349
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore```
bruh get use API calls, I know from sure because if it doesn't my bot would be broke right now
in discord.py maybe it uses cache
get doesn't make any API calls here
Neither in hikari nor discord.py and it's forks
if you want api calls use fetch
_users is a mapping in memory
btw both codes are same , right? I do prefer ur way tho cuz its short
I prefer using the or since It's shorter but does the same thing
Do you even know what ConnectionState does?
Is there any online ide where you can code project with libraries, other than replit?
it connecs to the websocket
.-.
No, clearly wrong
Bro.
https://github.com/Rapptz/discord.py/blob/master/discord/gateway.py this connects to the gateway and handles it
ConnectionState is the class that handles state
As the name suggests
Also still waiting for you to show real proof that get_ is an API call
Cause from what I see it quite clearly grabs from the mapping in memory
get is an API call?
That's what they think /shrug

Ah
@client.command(pass_context=True)
async def stealthrollout(ctx):
await ctx.channel.send("Stealth mode activated, hunting down aliens. Rollout!"),
member = ctx.message.author
role = get(member.guild.roles, name="Stealth Marine")
if ctx_sent >= 5:
await member.add_roles(role)
await ctx.send(f"hey {ctx.author.name}, {member.name} has been given a role called: {role.name}")```
Here's the code i want to know what should i write in if statement to make the bot assign the role to a user after sending !stealthrollout 5 times
never doubt andy
doubt andy and he will make u doubt u 😄
use command arguments, as you do for normal functions..
How could u explain pls?
async def my_command(ctx, arg1):
so basically whenever someone will do !my_command <arg> the arg1 variable will be <arg>
sorry i'm new to this i didn't get this
do you know how python function arguments/paramaters work?
No i'm still learning i'd really appreciate if u help me bit
Thanks mate
Do you help me?py @bot.command() async def casino(ctx, arg): cash = collection.find_one({"member_id": ctx.author.id, "guild_id": ctx.guild.id})["money"] if arg is numbers: if cash >= arg: money = arg if random.randint(0, 100) > 50: embed = discord.Embed(title="", description=f"Ты получил {arg} bebr", colour=0x843DA4) await ctx.send(embed = embed) collection.update_one({"member_id": ctx.author.id, "guild_id": ctx.guild.id},{"$inc": {"money": money}}) else: emb = discord.Embed(title="", description=f"Ты потерял {money} bebr", colour=0x843DA4) await ctx.send(embed = emb) collection.update_one({"member_id": ctx.author.id, "guild_id": ctx.guild.id},{"$inc": {"money": -money}}) else: await ctx.send("Бот, у тебя нету денег") else: await ctx.send("Бот, впиши число")
Well, it's like checking for a number (that is, whether the message is a number)
how do i check if a members dms are open or closed as i can message them or not
Numbers is well like a check on a number
I don't know how do check the number
It's a check
To number
I think he wants to check if it’s an integer
I don't know, I tried to check somehow whether the argument is a number and I picked up numbers
Typehint arg to int and it will convert it to an integer
Like, I need to write "if args.isdigit():"?
hello guys, anyone familiar with the pinksale.finance trending bar and how can it be manipulated? thanks!
Or "if args.isdigit() == true:"?
Nope
All commands
If you use this way then you would have to convert them to an int anyway because you use >= on them
That is, how?
I don't know how
arg: int
If it’s not able to convert it will raise commands.BadArgument and you can handle it in an error handle
will that work?
Is it also possible? Or is it possible only as we discuss?
Yeah that’s one of the little advantages of slash commands
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") objects. **Specifying both parameters will lead to an exception**.
and the fact that you dont need to make an arg a kwarg just to get more than one word of the arg
@slate swan :white_check_mark: Your eval job has completed with return code 0.
True
If I were an Englishman, I would understand the meaning of the text and commands better
You can disable slash commands in certain channels tho
well most of them are ephemeral by the developer, so thats a up up
Well yes admins can
Hmm.. can I check my relatively large code like this?
no you cant
and you shouldnt
Well , like to prescribe !e (that code)
you shouldnt paste large amount of codes
Oh, right, I forgot about that
how can you do that
property member_count: int```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Well I want to make a command which sends an embed. This embed shows something that I want to be updated after a specific time. I searched in stackoverflow and in other sites but I wasn't sure how to do this
or bot.users if u wanna show all the users the bot can see
I want it to be updated every 1-2 mins
you can use tasks, best option you'll get, a db isnt required really
Interesting
db is overrated
Hunter Hunter
Always speaking facts the opposite
have a minute?
Sure
how can i Auto-Changing Statuses
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
!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").
how do I make an error instance of an api for my discord bot?
like if the api only works when user says "test"
but if the user says "est" and the error from the api came in the console how do I make the bot respond with certain words when the error comes i know how to do with normal commands error like
if instance(error, commands......)
dont know about apis
Its your own API?
its from a website cant say name cuz rules
See their docs, they should be sending an error code other than 200
if they are sending 200, then, well, u gotta parse the response JSON, they send, yourself and see the input
BTW, mind DMing me the link?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord' has no attribute 'ButtonStyle'
uhh
ok ty
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() got an unexpected keyword argument 'style'
anyone know how to solve this i'm new to discord.py and py cord lol
code?
async def create(ctx):
button = Button(label="Click me!", style=discord.ButtonStyle.green)
view = View()
view.add_item(button)
await ctx.send("Hi",view=view)```
isinstance
how did you import Button?
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
How to add limit of amount in our command? Can someone help?
i used https://www.youtube.com/watch?v=kNUuYEWGOxA lol
This is the Ultimate Python Guide on Buttons with Discord.py or Pycord. In this video, I talk about how to create buttons in discord.py or pycord and how to respond to button clicks along with everything about Views. After watching this you'll know everything about Buttons and Views in discord.py or pycord.
This video might also apply to other...
oof
How do u get the custom_id of a component?
is that outdated
no
this one
docs
*is one of the developers of pycord
das nice
Just open the examples folder of the library's repo
tho he didn't do much
i am trying to make an error handler of an api
I know how to make error handler of discord commands but how do I make of an api these are codes
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, saucenao_api.errors.UnknownClientError)
await ctx.send('hm')
the error comes when it gets trigger but in console the bot doesnt says anything
mind showing the error in console?
nop,
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnknownClientError: Unknown client error, status < 0
that.... isn't the issue
didn't he say console
only UnknownClientError? tf
Show yr imports
from discord.commands import SlashCommandGroup, slash_command
from discord.ext import commands
import requests
import random
from lxml import html
import discord
import time
import asyncio
import aiohttp
import saucenao_api
from saucenao_api import SauceNao
import asyncpraw
from random import randrange

seems like an external module
its pycord, so yeah
oh right
Nah it's our most lovely fork
how professional
For me, no fork is lovely, but okay
Does anyone know how to fix the 429 errors?
Yea
rin 👌
Stop. Using. Replit.
kill 1 IN SHEll and rerun the repl
I don't have any other ide (i code on mobile)
hunter what else should he use?
I told him before also
Is there any online ide with libraries, other than replit?
Just get an Oracle VPS if he got a credit card
I don't
then..... u r fucked
Idk
Damn, I should really get that VPS and give u people free servers
ask your mom for a raspberry pi
Ok
That sucks
jk
any way to fix, please?
hmmmmmm weird tbh
on_command_error event won't deal with any other library's errors
but don't talk shit bout rasps
It will (:
i mean, u still have to make sure yr internet connection it perfect bruv...
Idk it does for me, at least a for a few libs
how wouldn't it
hmmmmmm
u live in australia or smth?
What's the difference between a normal gateway bot user and http bot
is nice
No
:)
English only lol
!ot thanks
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
those 8 bytes
💀answer please
https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/ext/commands/bot.py#L175 read the typehint of exception
discord/ext/commands/bot.py line 175
async def on_command_error(self, context: Context, exception: errors.CommandError) -> None:```
http is the API for doing stuff like sending messages and editing them, gateway is used to receive events like on_message and stuff
read the starting of the traceback
oh, how do we work with http bot then? (I use disnake)
U don't handle the low level stuff yourself, disnake does it itself
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, saucenao_api.errors.UnknownClientError)
await ctx.send('hm')``` but the code...
they aint tracking that error.
i was talking about this one /shrug
the endpoint used to interact with interactions like button click and stuff
Its fine
hi, Im making a timer command but i want the people who click on the reaction get pinged when the timer is over
if i am dumb its because im a newbie
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Examples
Usage
```py
# I do not actually recommend doing this.
async for user in reaction.users():
await channel.send(f'{user} has reacted with {reaction.emoji}!')
```...
hmm
@maiden fable I want it as like when the timer ends it should ping the users who reacted
Yea
once the timer ends, just do
reacted_users = await msg.reaction.users.flatten()
await ctx.send(", ".join(x.mention for x in reacted_users))
hunter discdb is just json but with a discord message instead of a file right?
idk how you can hate it, theres like 100 lines of code lol
Hate it as in, the idea lol
it could be a cool idea but you have done hardly anything
i was gonna make smthing like that
I mean, I cannot really do anything else lol
well
I am open to suggestions
you could make it so it encompasses multiple messages incase one gets too big
@maiden fable can i dm u?
you could make get_all_dbs method
No DM help, sorry @cosmic agate
ok
all sorts of methods
Make it relational, the channels acting as a table and the messages in it are a row
np
i was making that
Should also support data types
It should totally depend on the user how he wants to use the db and the messages. Tho u r most welcome to open a PR/issue
!indents
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
i was making mine sort of like sql but its hard to parse data and inputs
Bro... we are storing messages in a discord message, how tf can I support more data types
Parse it
?
Hmm
special syntax aka you put the datatype before the data lol
Lol
int | 3 and then you split it off of the | xD
I was gonna make a schematic language for slash commands
But then I got bored of it
the idea with disdata (the one i was making) was it was easy to use and easy to maintain a clean and smooth database - it was basically a replacement for json but not as fragile and frail
@maiden fable should i put the code before or after the timer ending code?
that would probably be the idea of discdb
Overall sort of a gimmick
before or after timer ending code?
after, ig?
ok sir
!Paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
?
paste your code here https://paste.pythondiscord.com/
then
Share the link
share the link
send the link..?
lmao
https://paste.pythondiscord.com/vixememufe @maiden fable this is my code
I will let someone else do the honours
@slate swan should i delete my originial message?
yes i am a certified noob
Yes it will be better
yeah prevent spam
I am half asleep rn and my braincells are already dead due to lack of sleep so I will pass
flexes 9 days of no sleep
ok
Mhmm whatever
XD
less than equals to
Someone needs sleep ic 👀
also
theres an arrow before equals
an infinite while loop
?
what if 0 is input
wdym
thats not negative, meths
U do know that maths is a big part of coding, right?
ik
We are just tryna help u here bruv
nvm, whats the issue?
I saw
lol
Smh
ha, so, mind explaining? @cosmic agate
hi, Im making a timer command but i want the people who click on the reaction get pinged when the timer is over
isee
soryy copy paste
something like timer bots
why not use tasks.loop
may I ask where this msg is coming from?
thats from @maiden fable code that he gave me
while True >>>>>
XD
Can become blocking
hmm
rip discord heartbeats
And rip yr console filling with log warnings
nah lol, not your fault, people can be annoying
so, where that msg from?
yeah like me
imagine
i just added the code that @maiden fable
i have no idea
I guess he wanted to use ctx.message lol
imma get new code
@cosmic agate it is a command?
I'll start crying
Take me with you
use message
instead of?
tomorrow, 4 pm GMT, crying session linkup at my home
ok
Hmm, cannot attend. Is there an option for a zoom session?
Ah
dw, we can e-cry
change msg to message
Phew I like that idea
does that help for the problem
smh
see
im a dumbass
STOP
SAYING THE
OBVIOUS
Calm down
where
Just go drink some water smh
msg.reactions
Calm down bucko
buckaroo
ok
okay I'm done, sasuke takes over from here
Someone is coming here after watching Beluga 👀
Forgot bucko is used for men
ok
File "main.py", line 81
reacted_users = await message.reaction.users.flatten()
^
IndentationError: unexpected unindent
b e s t i n t e n t e v e r
error i get
Why is a timer command so long
🤦♂️
My Love, Indentation
INDENTATION
first learn python
ahhhhhhhhh
tbh
my arch nemesis
Probably jumped straight to discord py lmao
just like I did ;-;
relatable
jesus
my updated code
indent your code, love
U do know that u randomly calling people love makes some of them uncomfy, right?
whenever u say jesus , i cried and laugh at the same time XD
my motive
amazing motive
Won't be surprised if mods come here any min
🔪
in the end, either i'll need help or will you, lmao
so, I'll leave hunter to the task
Eevee did that to me.
That’s why she’s not active in this server anymore
...
Eh yea, she messaged randomyl like yesterday or smth and coincidentally I was talking bout the time when she showed the ot command to lemon haha
whats wrong with calling people love
i need help
dunno
pls
me too
Never said anything is. It just makes some people uncomfy 🤷
hmm
@cosmic agate
why tho
@cosmic agate what are u trynna do?
No one is gonna help u rn at this stage. I suggest u to learn more about basic Python before jumping into discord bot making
Okay love
Dude how tf do u expect me to know anyways ot
sure, see you later
Bruh Ash
i'd be surprised if I did
lmao
Oh wait, how come u know whenever we talk bout u Eevee
hi, Im making a timer command but i want the people who click on the reaction get pinged when the timer is over
magik
I'm always lurking lmao
@cosmic agate please do not talk about self-harm here
Oh thanks for coming Scoff
You’re back
not anymore, bye
Thanks scoff
ok sorry im a idiot
lmao
Bye
Calm down now Transilp
bye
Will normal Commands get disabled in April 2022?
ok
imma head out too
i calmed
only if your bot is verified
starts talking bout u again in another channel to see if u r lurking in there too
i just want some help
XD
!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
lol
I’ll try that
@slate swan https://paste.pythondiscord.com/bizezewafo this is the updated code you asked ig
!ot let's take it there
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Hi, is there any clean way of setting parameter descriptions in slash commands? I used doc strings but they are deprecated. (disnake)
So the @bot.command() function won't work?
its not that it wont work
u will need to request for message intents
is just that you wont have message intents and therefore cant see them
thats weird
oh ok
So on_message won't work aswell as long as ur bot is verified?
correct
i see okay
unless the bot is mentioned in the message
I still can't help myself but laugh at the article discord wrote on message intent lmao
But why tho? Is there a specific reason for that?
hi, Im making a timer command but i want the people who click on the reaction get pinged when the timer is over
the discord servers were getting overloaded
which article?
they want us to move over to slash commands and stuff
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
oh that one
!d asyncio.TimeoutError
exception asyncio.TimeoutError```
The operation has exceeded the given deadline.
Important
This exception is different from the builtin [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError") exception.
discord is annoying
I hate slash commands
The error and what you might want to use
especially how when you make games in embeds they look shit on mobile
Same
@velvet tinsel https://paste.pythondiscord.com/bizezewafo this my code for timer
ikr
You have a crush on the bot.
But unlike your crush, the bot will open up and read the contents of your message every single time - how great is that!
F in the chat for the folks out there too shy to @mention their crushes.
i had to live with it for an year
i need help ik im idiot im a kid in the matrix
LOL
discord tries so hard to be relatable
im not a fan of discord as of right now tbh
lol what
Bro, u should really calm down. Calling yourself an idiot repeatedly will just demotivate you and lower your confidence
ik
everytime i make a game in discord it turns into a potato on mobile
until and unless i fix this problem im a idiot
The emojis go crazy as well
You know... I can help u code the discord bot, but first we can go through some python basics. Just grab a help channel and ping me in there. I will try to do my best to help u complete yr timer command
A wait_for isn’t hard 😳
Calm down
It even has a timeout kwarg
I am calm
That's easy imo, just save the id's of the ppl who reacted and then call them again after the timer had ended
That's like 15-20 lines of code
how are you gonna do the timer?
that’s like the shittiest implementation of a timer.
it’s not persistent through restarts
And even if it was. I doubt it preserves the state of the sleep.
Really?
Ye
can't you just use a wait_for? with a timeout
they said they wanted activation through reaction 
or they can just do some sort of shit
Tf dekriel
What are you saying dud
What are you talking about
I literally spent 5 minutes telling them to indent their code and still didnt manage to indent it
idk
😭
wait_for is used wait for when an event gets dispatched.
Average d.py users
No whatever you just said.
Like smh indents
I don't think soo
Nah it's not


