#discord-bots
1 messages Β· Page 149 of 1
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.
Can someone help me with this
ClientConnectorCertificateError?
Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, β[SSL: Certificate_Verify_Failed] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)β]
@uncut flume
Do i have to use @tasks.loop?
What about for Linux?
1st and main issue: you must not use blocking requests library in async app. Use aiohttp, check client quickstart on their docs
2nd issue is unoptimized code with tons of weird if-elif-else constructions. For example you could use a better construction instead of this
if "a" in text or "b" in text or "c" in text:```
You need to do
```py
if any(letter in text for letter in ("a", "b", "c")):```
I couldn't understand the logic of all those conditional operators but I am sure after a bit of thinking and restructuring it can be simplified a lot
What distro
Linux Mint
Ok I'll try to look it up
yeah i made that function like 8 months ago so no experience haha
What country are you running the script from @uncut flume
United States
Ok
@uncut flume try this https://github.com/Rapptz/discord.py/issues/5968#issuecomment-716222434
Summary I've got the aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VER...
Okey i fixed it. I'll now look into aiohttp. May i ask why aiohttp and not requests? and does aiohttp work with bs4
and do i still have to do tasks if i did this?
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
ahhhh
You have background loop, make it proper looking
Lol now you say so, i do have to wait when i use a different function while its performing the requests
okey, but is it just copy pasting the code under a @tasks.loop? because i use asyncio.sleep() inside the function itself
i can use @commands.has_role with role id right?
indeed
hm
= True is odd
you just mention the role ids and names there
this works different from the has_permissions deco :p
Happens
This solution didnβt work for me
Could you give me terminal's output after you executed those commands?
It's called "decorating"
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.
Yo
@uncut flume you made a typo I think
Anybody wants to help me with ChEmIsTrY?
What is that
It's update-ca-certificates, plural
I fixed it after that and it ran fine
You can see me type the command correctly under that line
No one :[
This server is focused more on helping with Python, not chemistry
Iβd suggest finding a homework help discord
oh okey, do you know if i can use bs4 with aiohttp?
async with session.get(url, headers=headers) as req:
s = BeautifulSoup(req.text, 'lxml')
``` gives ```File "/home/pi/bot.py", line 367, in testfunc
s = BeautifulSoup(req.text, 'lxml')
File "/usr/lib/python3/dist-packages/bs4/__init__.py", line 310, in __init__
elif len(markup) <= 256 and (
TypeError: object of type 'method' has no len()
I was just kidding ππ
ok
hello does anyone know how to make a inventory in nextcord/discord.py?
!d aiohttp.ClientResponse.text
coroutine text(encoding=None)```
Read responseβs body and return decoded [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") using specified *encoding* parameter.
If *encoding* is `None` content encoding is autocalculated using `Content-Type` HTTP header and *charset-normalizer* tool if the header is not provided by server.
[cchardet](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-cchardet) is used with fallback to [charset-normalizer](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-charset-normalizer) if *cchardet* is not available.
Close underlying connection if data reading gets an error, release connection otherwise.
Await it
yeah i already found it but thanks :))
π
@uncut flume and the export gave no output right?
No it didnβt
Eh, since bs4 is blocking too you either need to find its async alternative or follow this logic
def blocking_code(...):
# do bs stuff here
async def real(*args):
await asyncio.get_event_loop().run_in_executor(None, blocking_code, *args)```
oh
yeah i did everything with bs4 now
that would be a whole lot of rewriting for an old project lol
That thing in real() func if I highly oversimplify makes the blocking function async and you can run it without affecting event loop
I forgor
lol
π
Xd
ππ
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
π€
so i should just place that function in my code like that?
π
I told you what logic to use
Finally worked
Ye but I didn't mean that
Copy paste code
Oh
^ don't
EZ PZ
okey
xd
I wonder if anyone collaborated on my ai bot (probably nobody)
Copy paste always doesn't work π€·
After my xm ππΏ
Yeah, as expected, at least it got +1 star π€
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
π€·
Bro I drank weird coffee now I am farting with rate of 6 fpm
π
U just measured it!? XD
Yeah that's IT schizophrenia
Psychological disorder
Ohk πΏ
Now help me
With
What logging uses for in discord logger
!d logging
Idk lol
Source code: Lib/logging/__init__.py...
@vale wing Did you find any solutions?
That's builtin module
Cul
id is a built-in function name
It doesn't work after those commands right?
ohhhh
Another help, Anyways to react on discord gateway event?
What
Like session has been resumed or like
Ye something like dat
Also warning: cant give up error
Like this.
The only payloads you send via ws is heartbeat and the connection establishment/closure payloads
Any examples? I am bad at understanding xd
Like Identify, Resume
O.o
I am unsure what kind of info you need
Correct
Like listen
Any event when random session resumes pop up in console and bot sends a message or do some specific action on it
Any gateway event*
!d discordpy.logging
Whatβs the logic of modal class
Be more specific at least for me xd
@uncut flume do you have openssl installed
Like, if I use a command that calls up a modal, after I submit the modal how can I execute the code below βsend_modalβ instead of on_submit function
ahhhhhhhh
Like doing more stuff after sending modak
hello, can i ask for help in here
Modal*, why iam so bad at understanding bruh
I have an image i want to give an x and y axis using matplotlib, however i don't know how to then send the image (with the x & y axes) as a message (nextcord)
any ideas as to how to achieve that?
As long as it's discord bot related
@uncut flume try running openssl version -a
while True:
await channel.send(embed=discord.Embed(title="How much should we expect to receive in USD?", description="eg. $100", color=0x000000))
usd_amount = await client.wait_for("message", check=lambda x: x.channel==channel and x.author==sender)
amount = usd_amount.content
sendt = await channel.send(embed=discord.Embed(title="", description=f"Should we expect to receive $**{amount}** worth of {coin}?", color=0xa3a3a3), components=[Button("Correct"), Button("Incorrect")])
wtfsent = await sendt.wait_for("button", client)
if str(wtfsent.component)=="Incorrect":
continue
elif str(wtfsent.component)=="Correct":
if sendconfirm==False or receiveconfirm==False:
if str(wtfsent.component)=="Correct":
if wtfsent.author==sender:
sendconfirm = True
await wtfsent.respond(embed=discord.Embed(title="", description=f"{sender.mention} has responded to 'Correct'", color=0x1eff00))
elif wtfsent.author==receiver:
receiveconfirm = True
await wtfsent.respond(embed=discord.Embed(title="", description=f"{receiver.mention} has responded to 'Correct'", color=0x1eff00))
elif wtfsent.author==receiver and receiveconfirm==True:
await channel.send("ALREADY DONE")
elif wtfsent.author==sender and sendconfirm==True:
await channel.send("ALREADY DONE")
elif receiveconfirm==True and sendconfirm==True:
break
print(sendconfirm)
print(receiveconfirm)
await channel.send("pro fr")
Usually it brings you to on_submit interaction response function, but I donβt want that, I want it to execute the code in the original command after send_modal
is True better than == True
Like when a user use slash command u want it to send modal on that time?
i want it to ask the question once, once both people clicks correct it sends "pro fr", if one of the people clicks incorrect, it asks the question again, but the bot is not really doing what i want it to do
Or if var can only be of bool type like
is_good = True # can only be True or False
if is_good```
U can use else here if it's nnot true kinda simple
Yes, and after itβs submitted I want the program to execute the code in slash command async def instead of the response code in modal
When the bot reconnects, gateway sends all events it has missed after connection was lost iirc
Just add those code in on_submit function
Where u want it to execute after clicking submit
Those nested ifs, you should read a bit about code optimization
I am pretty sure the confusion happens because of them
@vale wing
Yes?
@tasks.loop(seconds=120.0) does this mean 120 seconds after the function inside it has started or 120 seconds after it has finished?
Every 120 seconds after start() was called
wait so if i have ```py
@tasks.loop(seconds=120.0)
async def restock():
That's a question for me too actually π
oh, but tasks.loop is infinite right?
Yeah as long as you don't stop() it or limit the amount of times it needs to be run
ahh okey, so a while true inside the function inside the task isnt needed right?
Correct
And if i want to run it i don't do restock() but i do restock.start() right?
@vale wing is this right, does the continue make the code go back to the start of the loop?
That's right but I am pretty sure wait_for("button") isn't. Iirc discord.py only has on_interaction event
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
See
yea im not using discord.py, im using discord_ui
But you shouldn't use event waiting for buttons, views are recommended
That's a submodule of discord.py isn't it
no, discord.ui is, discord_ui is something else (https://pypi.org/project/discord-ui/)
or atleast i hope so..? because im using discord==1.7.3
@bot.command()
async def removeword(ctx, *, word):
await ctx.message.delete()
with open(f"{ctx.guild.id}.json", "r") as f:
guilds = json.load(f)
form = f'{word}, '
form2 = ''
await removeworld(guilds, ctx.guild, word)
with open(f"{ctx.guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
await ctx.send(f"Added the word <> **{word}**.")
async def removeworld(guilds, guild, word):
form = f'{word}, '
re.sub(f'{form}', '', '').strip()
why wont this remove the words?
Don't use it. Latest version of discord.py has that functionality and you don't need to use those third-party crutches
they are very confusing to use, like to add views and for each button you need to create like 2 events and a view to put the buttons inside
my drop down menu stops working when i restart my bot
is there any way to fix it?
no code no answer
ok that was a little harsh dont ya think
does break exit the loop?
no
use persistent views, example in discord.py's GitHub repo ( examples/views/persistent.py )
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
is this right
ok thanks
ok not so simple question.
using matplotlib, i want to give an image x & y axes and then save the result as a png and send it as a message. How do I do that? Im using nextcord btw
!d nextcord.File you create a file using that png's path and pass it to your send method
class nextcord.File(fp, filename=None, *, description=None, spoiler=False, force_close=False)```
A parameter object used for [`abc.Messageable.send()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.abc.Messageable.send "nextcord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.abc.Messageable.send "nextcord.abc.Messageable.send")s.
also, matplotlib is blocking so just in case you already don't, throw it into an asyncio executor
ah, okay thx
im betting this won't work but i'm hoping this gives an idea as to what I am trying to achieve:
plt.imsave("map2.png", world_map)
await thread.send(file=nextcord.File("map2.png"))
See this for the example https://github.com/DevotedExuDevelopersTeam/EventMaster/blob/master/utils/image_generation.py#L250-L279
You specifically need whole 1st func and 4 last lines of the 2nd in highlighted lines
If they didn't get highlighted, those are 2 last functions in module
The solution is in these lines
Not really big
Non-async function draws the plot itself, saves it to BytesIO, seeks to 0 to make it readable and returns it, async one runs the blocking in executor so it doesn't affect event loop
this should work, and is correct
but there's a better approach that was suggested above^
Can help to know how can I make bot send message to everyone in the server?
Like in a dm?
Yes
You shouldn't mass dm members in a server, it's against TOS
I mean I have a discord bot
I want it to dm people if there is event or update etc
Dm everyone
Just ping everyone or have an announcement channel or have a special notification role
ping them in the server π€·ββοΈ
Tell him it's againsts TOS
So my bot would get banned or me?
Yes, discord has the right to refuse service by disabling or banning your account
Oof
Nah nevermind then lol
I just got my active developer badge don't wanna lose it that fast lol
π¦
why not? The update has already been released
Hmm really
yep
Oh yea discord need update lol
Lemme update it brb
Oh yeah now I can view it
Lmao

bro chillπ³
π
is there a way to create a background task without a loop? literally everything that comes up when I look for background tasks in discord bots is: @tasks.loop(), but that's not what I'm looking for - I want to be able to run code in the background, while keeping the bot running. I've tried:
task = asyncio.create_task(background_function())
await task
But when the task is awaited, the bot freezes and you can't send any commands to it (it seems the main thread is being blocked by the code being run). Is there a way to put that in the background, have it reply to the user when it's done, and not block the main thread?
It's saying exactly what the problem is
yep let me search what positional-only arguments are
you don't have to await it, you just leave it there
Is it to make a good looking giveaway slash command hard?
if I remove the await task, same thing happens
what does that slash mean?
Any argument in front of it is positional-only
running code, for now it's just a for loop that loops through 1 -> 100,000,000 so I can test it
!d asyncio.loop.run_in_executor 
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
I'm a bit confused on how to use this -- do I use the event loop created by pycord? (what do I pass in for the executor argument?)
await bot.loop.run_in_executor(None, func, ...)
that is, assuming func isn't a coroutine
otherwise you'd use create_task
in my original message:
But when the task is awaited, the bot freezes and you can't send any commands to it (it seems the main thread is being blocked by the code being run). Is there a way to put that in the background, have it reply to the user when it's done, and not block the main thread?
I'll try the run_in_executor though
depending on what you're doing, you'd use either run in executor, or create_task. Looping 100,000,000 times is blocking, so you'd use run in executor
that's what I thought - does the loop have to be an async function then?
it doesn't matter what the actual function is. What matters is what the function does
ok so two problems then:
the actual code is an exec() function, it's sort of meant to do different things depending on the situation
bot.loop.run_in_executor doesn't do anything at all, I'm wondering if that's because i'm using an extension, and therefore bot doesn't seem to be defined
I say that because I ran into a problem with bot not being defined earlier (instead of using bot.command I had to use commands.command)
in the example I gave, bot is supposed to be your commands.Bot instance
which is not defined in that file, because it's an extension... at least I think
if you're in a cog, you've probably defined an attribute called bot
i'm not in a cog, just an extension (separate file)
is that a command?
hm it is, so just use ctx.bot to access the bot
you don;t need the bot there actually, you can just ```py
import asyncio
asyncio.get_event_loop()``` to get the event loop
I just tried:```py
loop = asyncio.get_event_loop()
loop.run_in_executor(None, background_run, ctx, code_input, language)
and it says:
```py
/usr/local/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py:1910: RuntimeWarning: coroutine 'background_run' was never awaited
handle = None # Needed to break cycles when an exception occurs.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Can someone help me to make a slash giveaway command?
background_run can't be a coroutine, and you gotta await run_in_executor
ah
so now I'm a bit confused, I think background_run has to be a coroutine since I call await ctx.reply() in it
yes, background_run should be a coroutine because of that
and using create_task() causes the bot to freeze and stop working temporarily, while the code is running
yup
well, run_in_executor returns whatever the function that you passed returns, so you could figure something out there
you can await an run_in_executor as well iirc
how would I do that?
i'm already doing that
run_in_executor actually returns the result of your background_run which on calling would be a coroutine object, so just add an await before loop.run_in_executor
adding await, it still says background_run isn't awaited and needs to be
func (backgroun_run) can't be a coroutine, run in executor will just return the coroutine without executing it
random thought but could this be solved using threads? or are threads not really built for working with async
you shouldn't use threads
you can just expect the result from the executor and send it instead of making the function in executor do it ```py
@staticmethod
async def prepare_image_bytes(
attachment: hikari.Attachment, guild_id: int, channel_id: int
) -> None:
loop = asyncio.get_event_loop()
byted = await loop.run_in_executor(
None, GreetingImage._pillow_conversion, (await attachment.read()), guild_id
)
await bot.rest.create_message(attachment=hikari.Bytes(byted))
@staticmethod
def _pillow_conversion(initial_bytes: bytes, guild_id: int) -> bytes:
# returns bytes``` like i had this for a project
threading/multiprocessing with discord.py doesnt work well
yeah that's what I figured
is ctx.reply the only thing that's awaitable inside your function?
yes
hence, I'm trying what app_commands suggested
then you could return whatever you'd pass to ctx.reply
small problem -- it just returns the coroutine object: <coroutine object background_run at 0xaddress>
just dont use a coroutine, use a normal function for the blocking task
a smol workaround around your issue would be using a double await ```py
await ( await loop.run_in_executor(...))
yes this worked!!! thank you so much
gg, now lemme steal your christmas gifts
lmao I think I'll pass
that would still make stuff blocking
π i'll throw it in a gather or create_task then
but that;s kinda whole against the point of using the executor
wot
asyncio.gather and asyncio.create_task can process blocking coros without blocking....
Can someone help me to make a slash giveaway command?
anyone know if button labels can be multiline?
they won't render as multiline, but you won't get any errors if you add a new line
Hi guys !
message = 'My message'
image = 'https://www.mysite.com/myimage.png'
await ctx.send(message)
How can I add image to ctx.send(message) as an attachment please? :D
I see ^^
ty !
is it pycord?
Yes!
ctx.author._roles should return the list of role ids
can somone help with my code
File "main.py", line 148
)
^
SyntaxError: invalid syntax
Yes, it worked! Thank you!
Hey @gusty mango!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
help please
use a pastebin to paste your code and send
if he's using pycord and ctx is a discord.Interaction it's ctx.user no?
ctx is a discord.ApplicationContext
k
problem is that
what;s line 148 there? send the full error
whats worng with it?
can;t guess without checking full error
alr
line 149 and 147 are
wait
144-148: type=interactions.OptionType.INTEGER,
required=True,
)
]
)
@slate swan that is the line 148
π this code doesnt' make sense, what library are you using, and where did you get that code?
aliens ig
so
heres the full code
133-223 is all the code
@slate swan can u fix it?
?
send the full error
that is th error.
File "main.py", line 148
)
^
SyntaxError: invalid syntax
here
thats all the code i sent
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Someone can explain me what's happening here? :o
self.post_channel = self.ctx.guild.get_channel(channel_id)
I'm passing an int to .get_channel()
it is
!error
@glad cradle its invalid sytanax error
have you read
Why do people get discord developer badges of They donβt develop? A guy wanted to pay me to help him get the badge, Thatβs such a waste
The over hype of the badge thats why people want it, it makes you look "cool"
After all who doest want to be a cool developer
import discord
client = discord.Client()
@client.event
async def on_ready():
print("Bot is ready!")
@client.event
async def on_message(message):
if message.content.startswith("/hello"):
await message.channel.send("Hello, world!")
client.run("YOUR_BOT_TOKEN_HERE")
The Ai genuinely understood the assignment which is scary
I know its basic but the fact that an AI could understand the task is a little scary
Guys, could you please help me with another problem π So I don't know how to add an image to my status to my discord.py bot (I'm using Py-cord). I tried using Dict but something's not working π¦ (I've tried changing the variable's name to "assets" too, but it's still not working)
my embed.set_image(url=self.proof) somehow isn't working, I've tried to print(self.proof) and it's indeed a valid url I'm confused, can someone help me?
In what way is it not working? The image is stuck loading, it doesn't show as part of the embed, it errors, etc.?
it doesn't show at all and i'm not getting any error
Can you show the rest of the code for your embed?
here:
def server_report_embed(self):
embed = discord.Embed(color = 0xff0000, title = 'Scammer Server')
embed.set_image(url=self.proof)
embed.add_field(name = 'Server ID:', value = f"`{self.id}`", inline = False)
embed.add_field(name = 'Owner:', value = f"{self.owner}\n`{self.owner.id}`\n<@{self.owner.id}>", inline = False)
embed.add_field(name = 'Reason:', value = self.reason, inline = False)
return embed
all the other values are working fine and the embed is popping out
but the image isn't attached at all
What's the image url?
https://media.discordapp.net/attachments/989245983873437696/1049455757613076521/image.png
it varies but it's an image that the bot takes from attachement
the image shows in the channel when the command user uses the command and the bot reads it fine
I'm not seeing anything clearly wrong here. self.proof is just a string containing this url?
yeah
Someone, please ? π
I also tried str(self.proof) didn't change anything i'm really clueless
those urls look a little off, doesn't look like they lead to image files. Try getting a url that leads directly to an image.
in the same function as where you create the embed, do
print(self.proof, type(self.proof))
I deleted pycache folder it worked lmfao
π
ty for your help tho
π
I've changed it to https://i.ibb.co/G9vD5T3/ce1ab62054e2bf05f117e9c6bad552b6.png but it's still not working
make sure it's assets too, not asset
Yes, I've changed that too
Guys can server ID and user ID be same? like can they conflit?
Discord IDs will always be unique.
That's why they've named them "snowflakes"
https://discord.com/developers/docs/reference#snowflakes
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
oh okie tyyyy
you can't do that on bots.
Guys, how do I pass an image to a slash command?
can i get some help as to why this wont run?
as per the error message, you need to enable the corresponding privileged intents in the developer portal - in your case you used discord.Intents.all(), so that needs the Presences, Server Members, and Message Content intents enabled
i see, so is this the permission level for the bot?
this right?
i wouldnt say "permissions" since that term often relates to server permissions, privileged intents are their own thing, and if your bot is in 100 servers discord will require you to verify your bot in order to use some of those intents
i havent seen what an attachment option looks like on slash commands before, but if you're using discord.py 2.0 you can typehint one of the parameters with discord.Attachment to make it an attachment option, e.g. py @bot.tree.command() async def my_command(self, interaction, file: discord.Attachment): ... # do something with file
typehint discord.Attachment
Great! Much obliged!
getting back into python. could someone catch me up on the status of discord.py? i have an old moderation bot i used for personal purposes. and its no longer working. if anyone could help me out thatd be great. π
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "/home/container/cogs/ticket/timeout.py", line 35, in tickettimeout
channel = guild.get_channel(ticket['_id']) or await guild.fetch_channel(ticket['_id'])
AttributeError: 'NoneType' object has no attribute 'get_channel'```
why am i getting this error? ive tried guild = self.bot.get_guild and guild = self.bot.get_guild or self.bot.fetch_guild
but its stillr eturning none
and the guild isnt none, since ive tried a var that i use in multiple other files and striaght up hard coding the id
dpy continued development and v2.0 released 4 months ago, latest version is v2.1 and they have a migration guide for their breaking changes
https://discordpy.readthedocs.io/en/stable/migrating.html
the error doesnt lie, but given that you're using a task loop, did you add a @before_loop to make it wait until the bot was ready?
oh yeah i remmeber this, its funny bc it happens on some bots and not others, just depends how fast shit loads haha
How do i do this?
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
for example: ```py
@tasks.loop()
async def my_loop():
...
@my_loop.before_loop
async def before_my_loop():
await bot.wait_until_ready()```
ahh makes sense, so that just wont run the loop till it starts bascily?
yeah
hi all, just one very quick question this does not properly ping the user on discord, user_id is holding a string with the discord user's ID, so it will say "@ID" but not ping them, any solution? I use
import discord and
from discord.ext import commands
It needs to be in the format of f"<@{user_id}>"
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, 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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
use allowed_mentions=False
but if its false then it wont let me mention them right?
yes
how would i format it into the line of code?
I already can mention, i embedded the @ sign into the ID, I want to discord ping them and give a notification to their discord app
so it will say "@ID" but not ping them, any solution? .
?
. phrase ur question properly
What i mean is that I cant @ the specified user,
I want to do
@shrewd apex hi
for example
I have changed it to that and it doesnt work, it reads the text as you have it without the blue ping
string that holds whatever discord ID i want to specify
show the whole command/function
honestly now that im testing it, could just be a logical problem because it wont even do this @dull horizon, bot does not respond
Show us a picture of what it looks like
This is the program as a whole
from discord.ext import commands
import time
import asyncio
import random as rand
import os
compliments = ["1","2","3"]
client = discord.Client(intents=discord.Intents.default())
bot = commands.Bot(intents=discord.Intents.all() , command_prefix= "!")
user_id = "360933425361715200"
def getToken():
token = open('token.txt','r').read()
return token
token = getToken()
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == 360933425361715200:
await message.channel.send(format(message.author.mention) + " " + compliments[rand.randint(0,2)])
if message.content.startswith("!sayhi"):
await message.channel.send(f"<@{user_id}>" + "hi")
if message.content.startswith("!compliment"): #roastList[rand.randomint(len(roastList))]
await client.send_message(message.channel, compliments[rand.randint(0,2)] % user_id)
if message.content.startswith("!randomkick"):
if rand.randint(1, 20) == 1:
await message.channel.send("Bye Friend")
discord.kick(user_id)
if rand.randint(1, 20) != 1:
await message.channel.send(format(message.author.mention) + " " + "Roll again!")
client.run(token)```
token.txt just holds the bot token
if the user that i target says anything in chat, they will be complimented from a list i have not fully specified yet, that part works. But the ! commands do not work
haha π
any good pagination examples?
you have set your bot prefix to !, you need to define a function so commands starting with !, idt on_message will work for commands ?
Thank you!
@client.command()
async def sayhi(ctx, args):
await message.channel.send(f"{ctx.author.mention} hi")```
try this
can i do without ctx? i already have other imports
ctx is the context passed with the command
You really gonna leave me to dry like that my man
from discord.ext import commands
import random
bot = commands.Bot(intents=discord.Intents.all() , command_prefix= "!")
user_id = 360933425361715200
def getToken() -> str:
token = open('token.txt','r').read()
return token
token = getToken()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author == bot.user:
return
if message.author.id == user_id:
await message.channel.send(f"{message.author.mention} {random.randint(1,3)}")
await bot.process_commands(message)
@bot.command()
async def sayhi(ctx: commands.Context) -> discord.Message:
await ctx.send(f"Hi {ctx.author}!")
bot.run(token)```
@dull horizon
figure the rest out urself
Don't use this thing at all
Dpy 2.0 has support for components, no need for third-party libs
okay thx
well it doesn't exist like the error says 
not sure where you got that code from, but you should try to find an updated version
Good advice 
i fixxed it thx tho
that key doesn't exist in results
IT DID
maybe print it and see what's in it
Ohhhh
from utils.database import Database
anyone know why this import isnt working for me? Ive tried to pip install a couple things but hasnt worked
Is there any error message
when i try pip install db-utils I get this
but idk for sure if db-utils is the install that will make
from utils.database import Database be read as a module
click the link in the error and install c tools how much more obvious does the error message need to be
update if u already have it
what?
from utils.database import Database is prolly not a package its likely a module or another py file in the project
that makes sense thank you
Hi guys
Is it possible to make a modal input that only accepts numbers? (Without checking when the user clicks send, I mean directly)
nah you would have to manually check. no way to force a user to input an int
U can do in slash command tho xd
No, it has to be a modal
damn
Then check if user's input is int or not if int then restart
yeah he was trying to avoid that
i mean you can have the placeholder be a number, if they submit something thatβs not an int, reopen the modal and just make it clear they need an int
Okay
send a Rick roll if they enter non-int value π€Ί
skill issue, get a VPS

class persistenetViewBot(commands.Bot):
def __init__(self):
intents = discord.Intents().all()
super().__init__(command_prefix = '^', intents = intents)
async def setup_hooks(self) -> None:
self.add_view(View())
client = persistenetViewBot()
i used this code from internet to keep drop down menu working
but i am getting error for adding the prefix second time
idk how the code works so i need help
What's the error
when i use a command i get this
i tired setting prefix to none but it ended up having more errors
well it does
the program is calling the command 2 times
one for client = commands.Bot(command_prefix='^', intents = intents)
and for second time in persistent
What does that mean
ok wait
i think i have a fix (nvm dint work)
lol
i defined the client on start of program
but the code i copied for persistent is defining client again at the end of program before client.run
thats causing the error
What
multiple client instances moment
yes that
thanks
i tried others methods of making it persistent but none worked
this one is wroking but with an error everytime a run a command
setup_hooks inside init moment
idk what i did there
i just copied pasted it.
i will learn how it works later for now i just wanna run my bot
you copy pasted it wrong
why you're sleeping on Bot error
is there a limit on how many times you can edit a message?
my bot is error less π
π
Technology of the future
Pretty sure there is a days limit for messages, E.g you cannot edit a message that's older than two weeks
Other than that if you stick in 5/5s there is no limit
discord renders the (0) so poorly in the preview
( 0 )
Do it π
32 character limit
Sedge
lambda*
Hmm
O.o
Help me with ChEmIsTrY
Loaded up stable diffusion and immediately heard my GPU fans rev like a motorcyle
im in a chem.class rn lol, learning ligands
Ligands 
Ligands are fun, learned them during my second year or first year of college I'm not sure exactly when
Negative feed back loop diagrams might look weird at first but they get easy
In a biology context not chemistry
....
WHAT'S INSIDE THE FROG DUDE TELL MEEE AHH
Organs and stuff
There are some frogs that have been bred to have transparent skin
Allowing students to easier practice on them

;-;
yo Andy, how do you manage to use attrs with pyright ;-;, I'm sick of it already
pyright is treating attrs as dataclasses for some what idk reason
attrs is dataclass
except that its not,
#type-hinting message
Holdon let me load up a test env
also had reportImportCycles under TYPE_CHECKING but ignored it
I'm pretty sure eric said something in a GitHub issue about this, relating to bad design or something
You can just go into pyproject.toml and ignore reportImportCycles if on strict
Also for the attrs thing yea that isn't supported
I thought this was for some other stuff like annotations with field()
yeah thats what I did
Can you explain more about your _bar thing
Are you trying to make _bar as private var
yeah it was actually for my api wrapper, the actual implementation was ```py
class SomeDiscordObject:
_client: MyGatewayClient
but ended up doing so in the end
can someone walk me through main.py, for a discord bot. i have all my cogs but for some reason everytime i try to setup my main i just keep getting errors (i would imagine because idk the new discord.py)
show code and whats the error?
okay one second
Traceback (most recent call last): File "main.py", line 39, in <module> client.run(os.getenv("Aura")) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run asyncio.run(runner()) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner await self.start(token, reconnect=reconnect) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start await self.login(token) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 580, in login data = await self.http.static_login(token) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/http.py", line 801, in static_login data = await self.request(Route('GET', '/users/@me')) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/http.py", line 680, in request raise HTTPException(response, data) discord.errors.HTTPException: 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.
Rate limited
short answer: don't use replit

rate limited, my solution was to just "kill 1" in console
good idea xD
do you guys host directly off your client or do you use something else?
i don't host my bot projects
have my own host server π
import attrs
@attrs.define(kw_only=True)
class SomeDiscordObject:
client: str = attrs.field(on_setattr=attrs.setters.frozen)
obj = SomeDiscordObject(client="foo")
obj.client = "bar"
``` you could probably freeze it instead
could i dm you? i dont want to fill chat with a bunch of my silly problems
thank you, I'll try when i get home

um sure ig
dm this chat
The name issue still persists but instead when doing obj.client = ... it'll give an error
So, obj.client should be "immutable"
How do i do something when user clicks a reaction
listener, or wait_for
oh yeah it is not changed once the class is initialised so that works
Howww????
!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.11)"). 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.11)") 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.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
how do I move a global variable to another file ?
No documentation found for the requested symbol.
how do i use wait for, can u show me a example
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
click the docs
nice, so now users cannot change the client manually
Also TIL attrs strips _ from the attributes
there is an example in it
yeah thats nice but would have been better if it was an optional functionality instead
imo
@bot.event
async def on_ready():
global tdict
tdict = {}
@bot.event
async def on_voice_state_update(member, before, after):
author = member.id
if before.channel is None and after.channel is not None:
print('1')
t1 = time.time()
tdict[author] = t1
elif before.channel is not None and after.channel is None and author in tdict:
t2 = time.time()
print('0')
print(t2-tdict[author])```
how do I get a variable out of here and move it to another file ?
thanks
You can use metaclasses
But it get's a bit more complex
Uhm, depends on which file
if txt, then just open it and write
move to the file where the command is located, that is, the .py file
uhm... you could just import it in the file where your command is, but if this variable changes during the bot runtime, then you would need a db or a JSON file to store it
well , json is needed so that it is saved when the bot is turned off , and until it is turned off , the file is not needed ?
wdym the file is not needed?
which file
please tell me how to transfer this variable to a command that is in another file
alrdy told you?
no
Hey guys, im using disnake and autocomplete. Im using a subcommand so its /mvp timer but I want to also make an autocomplete for another thing called miniboss so /miniboss timer
@timer.autocomplete("name")
async def mvp_name_autocomp(self, inter: disnake.ApplicationCommandInteraction, string: str):
string = string.lower()
if len(string) == 0:
return []
return [i for i in MVP_NAMES if string in i.lower()[0:len(string)]]
how
How do I make autocomplete for /miniboss
The same way you just did for the previous command
both have the same command name timer
theyre sub commands
@commands.slash_command()
async def mvp(self, inter:disnake.CommandInteraction): ...
@commands.slash_command()
async def miniboss(self, inter:disnake.CommandInteraction): ...
And what's the problem
and what exactly then do I need to write in the command where the time in the voice is written {what will I need to write in these brackets ?}
so i want a different autocomplete for the timer command
cause its going to be
@mvp.sub_command()
async def timer():
@miniboss.sub_command()
async def timer():
Just set a different name for the callback function
And set the name kwarg in sub_command decorator
you don't know how to read json files?
Oh I forgot about that. Thank you!
not work...
dateFormat = "%d/%m/%Y %H:%M:%S"
@bot.event
async def on_voice_state_update(member, before, after):
with open('data/voice_leaderboard.json', 'r') as file:
voice_data = json.load(file)
new_user = str(member.id)
guild_id = str(member.guild.id)
# Update existing user
if new_user in voice_data[guild_id]:
voice_leave_time = datetime.datetime.time().strftime(dateFormat)
voice_join_time = voice_data[guild_id][new_user]
calculate_time = (datetime.datetime.strptime(voice_leave_time, dateFormat) - datetime.datetime.strptime(voice_join_time, dateFormat))
voice_data[guild_id][new_user] = str(calculate_time)
with open('data/voice_leaderboard.json', 'w') as update_user_data:
json.dump(voice_data, update_user_data, indent=4)
else:
if member.bot:
return
else:
new_voice_join_time = datetime.datetime.utcnow().strftime(dateFormat)
voice_data[guild_id][new_user] = new_voice_join_time
with open('data/voice_leaderboard.json', 'w') as new_user_data:
json.dump(voice_data, new_user_data, indent=4)```
!doesntwork
oh they still haven't added this tag
sadness
wait that's not what i meant
ok so what i mean is u gotta send your problem too
not only code, i dont wanna guess, what is your error
@silk fulcrum does it seem to me or is it impossible to do this in python at all ?
there's solution to anything
that's how programming works
that's almost how world works
except for the part where it doesnt
other than that, world also works like that
Relatable
@silk fulcrum I've been trying to do this for oh, oh, how long and I don't understand how. And I perceive the words read the documentation as (I'm a shit who only knows how to send to the documentation)
beep boop, it's just noone wants to explain, especially when there are docs that you can read. Especially this one :bruh: https://bear.im/code/parsedatetime/docs/index.html
I don't understand how it's written!!! It's a horror how it was necessary to beat a person to write documentation for discord.py
by the way, if you would mind coming back to your problem a little bit, what error do you get? And if you don't get one, what do you expect from your program and what happens instead?
Are you kidding me? I don't understand the official documentation, you threw me off even worse, just white noise
That's the point, it was a joke, nobody can read that documentation, I tried, and I couldn't, I just threw this lib out the window
Yeah, I was expecting it to be a problem with a filename
I also had lots of those
Man read it
Yall beginners are like "OMG CRAZY BIG RED TEXT SCARY ima ask pro ppl who aren't scared"
It's easy
Sure 
Also you gave 2 tracebacks
How to make command only work for me (bot owner)
I don't know how is it correctly done, but I myself just go to the file in a file manager, and right click it, and choose "Properties" > "Details" and copy the Folder path, then just write the name of the file after it
oh Russian
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
I forgor ext π
This work for slash command?
forgorable, understanrable
this work for slash command, but other way
π
what
Lol
How the heck is that called
?
Hmmm
ΠΏΡΠΎΠ΅ΠΊΡΡ Π½Π° Python
Dpy placed app commands decos into another module for no reason, why not just make common ones compatible with them like in disnake π
why is robodanny not here
Proekti na python
I still don't know tho how to make command only for bot owner (slash command)
Just make your own check at this point
yeah 
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
Try the common deco anyway, might work
I just made a normal text command for only myself, i dont need slash commands as an owner
what
Dpy has lots of nonsense stuff that's why I prefer disnake
Hmm
π¦΅π³π¦΅
Tf is disnake lmao
Dpy fork
that's why I make my own everything
not cus i have nothing to do, I just enjoy making my own things
except for something big, like a discord bot
You code in binary? π§
but you know, i started it
i wish i could
Nonsense stuff like what?
π³
Why would you make an owner only Slash command
Everyone will see
Make a text command, or sync to a testing guild or smth
"Full sync control" which commonly ends up just as a thing you always gotta do, no shortcuts for inter.response.send and inter.followup.send (again they call it "more control" but I see it as an inconvenience). I like their modals implementation tho
Separate checks for app commands for no reason (correct me if there is)
WASSUP
pycord tried to fix the same things( 2nd point) by wrapping app interactions to a context and now thats a bad impl
the only design mess i feel about dpy is having a single interaction class for all interaction types
That too
Disnake has differentiation of interaction related events like on_button_click which removes the need for additional checks
:[
Fair enough, disnake sounds like one of the better forks
i believe that was for compatibility with old dislash.py but yeah thats indeed nice
hello, wassup
Even tho as a relatively experienced developer I can use dpy with no problems, disnake offers many things that make development faster and more comfortable
Me very gud, what bout u πΏ
Like??
Mentioned above
fair to say disnake is the best fork
pycord users stay mad
my bot.wait_for("reaction") doesn't work at all
done with classes, changing
reaction_add iirc
you need member intents
oh wait yeah that too
i do have bothh
reaction_add as exenifix said
Online classes?
Reaction add requires members? Isn't there like a separate intent for reactions
offline
!d discord.Intents.reactions
Whether guild and direct message reaction related events are enabled.
This is a shortcut to set or get both guild_reactions and dm_reactions.
This corresponds to the following events...
reaction = bot.wait_for("reaction")
await bot.add_reaction("βΆοΈ")
if reaction == "βΆοΈ":
print("go ahead")
is anything wrong with it
its required for the "user" argument
@slate swan
Multiple people have said it's reaction_add
Please pay attention to chat
noo i have done the reaction_add on the real code
i forgot to add it in this example
Why don't you show us your real code
you don't have a proper check, your reaction is probably just getting ditched cause bot tracked another reaction already
msg = await ctx.send(embed=page1)
await msg.add_reaction("βοΈ")
await msg.add_reaction("βΆοΈ")
i = 1
r = await bot.wait_for("reaction", timeout=30)
await msg.edit(embed=pages[i])
if r == "βΆοΈ":
if i < 10:
i += 1
await msg.edit(embed=pages[i])
elif r == "βοΈ":
if i > 1:
i -= 1
await msg.edit(embed=pages[i])
Ah okay found that
Oh yeah you don't have a check
how do i check
raw_ events are still usable without that ( reason why its recommended over direct Reaction_add/remove)
!d discord.Client.wait_for the check kwarg
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.11)"). 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.11)") 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.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
!d discord.Client.wait_for
Yeah I read that thx
There are examples here
When the 2 waitfors
its not a school, just coaching classes. so they allow phones
What library do u guys use for your bots
How about forks
Wym
Its back
I know
Development continued
It depends what you need tbh
Personally I would stick with discord.py
Same
However now there are options like disnake or nextcord
disnake 
What do u prefer between both
I've never used either
So I can't give an accurate opinion
Though disnake seems to be the most popular
hikari with lightbulb
i use it because of the low level API it provides
But the development is sleepy there ,
which is totally different from discord.py's
But the code is clean
welp yea
they released forums just yesterday
the development is slow because there's less contributors and the code quality is much higher than average
i feel lost when i read their src
Also hikari docs should get a fully rewrite
Theres a difference in quality and complexity 
your wish has been fulfilled
LMFAO
https://docs.hikari-py.dev new docs
released yesterday
its a bit buggy on phone
Because fuck rtfd
both can co-exist
i prefer the old hikari docs tbh but yeah this ones easier
search was broken in old one
Yep, but if we're talking about the src of dpy i wouldnt say its the best quality just over complex
discord.py is at the verge of complexity
I like simple abstractions what can i say
π€¨
i noticed pycord changes their docs theme too
they're using furo instead of the custom discord.py theme
the backend source is what we are talking about rn, not how easy it is to use.
Oh lol
I was going to say, its extremely easy to learn and use
I didnt watch a video I just read the docs and came here if I had an issue
Furo is so goodπ©
I want to try mkdocs tbh
Hi just wanna ask what should I pass in for ctx?
I kept getting this error:
TypeError: expected string or bytes-like object
Here's what I tried:
h = commands.MemberConverter()
mem = await h.convert(ctx, argument=user.id)
if you have ctx and a user id you can just use ctx.guild.get_member
your command context π€·ββοΈ , not sure if error is coming from this part tho
also curious where you're getting user from
like the user input
it's a command parameter?
yeah yeha
if so, you can typehint it to discord.Member and get a Member object directly
(discord.py uses MemberConverter for the conversion)
i know but let's say if the user passed in a user id which is not in the server, it would just skipped the user.joined_at which can only fetchable through discord.Member (im currently working on user info command)
So I want to convert it to discord.Member if the user is in the server
rather than discord.User
Can someone help me? My bot isnβt online
import nextcord
import asyncio
from config import TOKEN
class CreateTicket(nextcord.ui.view):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Create Ticket", style=nextcord.ui.Buttonstyle.Blurple, custom_id="create_ticket:blurple"
)
async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction)
await interaction.response.send_message("A ticket is being created...", ephemeral=True)
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(CreatTicket())
self.persistent_views_added = True
print("Persistent views added")
print(f"Bot is up and ready | Logged in as {self.user}")
bot = Bot(command_prefix='!', intents = nextcord.Intents.all())
@bot.command()
@command.has_permission(manage_guild=True)
async def setup_tickets(ctx: commands.Context):
embed = nextcord.Embed(title="Create a ticket!", description="Click the `Create Ticket` button below to create a ticket. The server's staff wil be notified and shortly aid you with your problem")
await ctx.send(embed=embed, view=CreateTicket())
bot.run(TOKEN)```
And where do I need to insert my token?
is this a cog file or the main file?
Main
insert it at
bot.run(TOKEN)
Is it then fixed?
from config import TOKEN
Oh idk
just wanna ask if u copied the code or smt
I watched a tutorial
just remove this line and put your token as a string in the
bot.run(TOKEN)
line
@vale wing I figured out the issue by the way, thank you for the help!
so
bot.run("YOUR TOKEN HERE")
I was on a school network so they were blocking the connection to discordapp.com:443
Ty
Its still not online can you help me?
import nextcord
import asyncio
from config import TOKEN
class CreateTicket(nextcord.ui.view):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Create Ticket", style=nextcord.ui.Buttonstyle.Blurple, custom_id="create_ticket:blurple"
)
async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("A ticket is being created...", ephemeral=True)
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(CreateTicket())
self.persistent_views_added = True
print("Persistent views added")
print(f"Bot is up and ready | Logged in as {self.user}")
bot = Bot(command_prefix='!', intents = nextcord.Intents.all())
@bot.command()
@commands.has_permission(manage_guild=True)
async def setup_tickets(ctx: commands.Context):
embed = nextcord.Embed(title="Create a ticket!", description="Click the `Create Ticket` button below to create a ticket. The server's staff wil be notified and shortly aid you with your problem")
await ctx.send(embed=embed, view=CreateTicket())
Can someone please help me with that. My bot isnt online! ^^^
try putting bot.run("MY TOKEN IS HERE") at bottom
import nextcord
import asyncio
from config import TOKEN
class CreateTicket(nextcord.ui.view):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Create Ticket", style=nextcord.ui.Buttonstyle.Blurple, custom_id="create_ticket:blurple"
)
async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction)
await interaction.response.send_message("A ticket is being created...", ephemeral=True)
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(CreatTicket())
self.persistent_views_added = True
print("Persistent views added")
print(f"Bot is up and ready | Logged in as {self.user}")
bot = Bot(command_prefix='!', intents = nextcord.Intents.all())
@bot.command()
@command.has_permission(manage_guild=True)
async def setup_tickets(ctx: commands.Context):
embed = nextcord.Embed(title="Create a ticket!", description="Click the `Create Ticket` button below to create a ticket. The server's staff wil be notified and shortly aid you with your problem")
await ctx.send(embed=embed, view=CreateTicket())
bot.run(TOKEN)```
Like this? ^^^^
Glad you sorted it out π
Sounds like venv issue to me
?
yes
Ss your bottom right corner
Done already
Ok take a ss of whole screen
Okay?
π
left side of VSC
Bro
Locate the file
You need to open a folder with this file
Done thay
That isn't required
Ss now please
okay
Idk i did what the guy said in the video
Fyi hardcoding token into project is bad for security π€
but where is the token then?
^
Lemme fetch a guide on tokens for you rq
You just shared your token right?
reset the token brother
Ye π€£
did already
So now it needs to work
@mellow verge https://tutorial.vcokltfre.dev/tips/tokens/
A tutorial to help you make better Discord bots.
Ty
yo
@commands.has_permissions(administrator=True)
async def purge(ctx, limit: int):
await ctx.channel.purge(limit=limit)
await ctx.send('Cleared by {}'.format(ctx.author))
await ctx.message.delete()
@purge.error
async def clear_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You can't do that!")```
this is my code, but when i want to clear it deletes my clear message too (!clear NUMBER)
and i want to not count the !clear NUMBER and delete the 'Cleared by {}'.format(ctx.author) after some seconds
how do i do that?
use delete_after()
how do you answer a "/" so that everyone on the server can see it?
like see your answer or see that you ran the command?
based on defaults im assuming first one and im not sure its possible unless you add it into the bot response
interaction.bot.get_guild no?
well when i use my command it says "only you can see this" how do i make it so not only me can see it
ephemeral = False
should be just interaction.client.get_channel
im not 100% but im 90% sure itll get the category if thats the id passed
oh alright thank you so much!
np
How can i make a task that doesn't start again after certain seconds? Because thats handled in the function itself with while true. If i let tasks.loop handle it the list i need for the next iteration won't be saved, and then i would have to use global so regular tasks.loop basically isn't an option
Could you maybe do @tasks.loop(seconds=None) or something?
Why are you even using a while loop in the task
If i let tasks.loop handle it the list i need for the next iteration won't be saved, and then i would have to use global
i have a loop existing of 2 parts that creates 2 lists, i need the second created list in the next iteration but if i don't use the while loop with regular tasks this function runs again and then final_list (the second created list) is set to null. If i don't do it there it will be undefined```py
async def restock():
logchannel = bot.get_channel(960147355691253800)
await logchannel.send('Restock monitor on')
global fl_oos
global sizeoos
final_list = []
count = 0
fcount = 0
global restockkk
restockkk = True
Does that make sense?
!d discord.CategoryChannel.text_channels you can iterate through these and check if any have the user's username as its name
property text_channels```
Returns the text channels that are under this category.
Good evening, I'm looking for a way to integrate a key/license system for the script associated with my bot discord to prevent it from being re-shared
You can help me ?
Can someone help? problem: File "main.py", line 161
if round_length < 36:
^
SyntaxError: invalid syntax
code: https://paste.pythondiscord.com/xeqilegagu
you missed a colon above that line
so
@commands.has_permissions(administrator=True)
async def purge(ctx, limit: int):
await ctx.channel.purge(limit=limit)
await ctx.send('Cleared by {}'.format(ctx.author), delete_after(10s))
await ctx.message.delete()
@purge.error
async def clear_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You can't do that!", delete_after(10s))```
?




