#discord-bots
1 messages Β· Page 764 of 1
But then, it depends on the cache
No, I'm just questioning the use of your function
like 'why would you get all deleted messages and store them in a txt?'
When i use the purge command it gets all messages that were purged and puts in txt
I store the messages so mods can view what was deleted
I'll send the file in a logging channel..
ah, ig that kinda makes sense
you don't have to store the file locally btw, you can generate it and send it straight away without ever needing to store it locally
that's the best practice I'd say
!e import discord
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
why
because letting someone run a discord bot with an eval command is a great idea
oh its discord.py anyway
dont need import discord its a dc bot
!e if message.content == 'hi':
message.channel.send('hi')
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | message.channel.send('hi')
003 | ^
004 | IndentationError: expected an indented block after 'if' statement on line 1
nothing like that would work.
ahhh
its a sandboxed eval
no its just i cant do it here on phone on discord
cant do intendet block on phone on dc
only visual studio mobile or smth lien that
it only runs things a basic python installation does..
!e if message.content == 'hi': await message.channel.send('hi')
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: 'await' outside function
was await needed or no?
it is , but once again
thats not what the bot is meant for
!e if message.content == 'hi': message.channel.send('hi')
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'message' is not defined
a bot command channel
more specific next time aight?
it's in a help category
I wonder if it's against the rules to try and test possible vulnerabilities. Probably not
use eyes
#bot-commands
its not , is indeed better if someone does that
I see
he tried it in #databases too 
could have directed me to the channel instead of complaining lel
also where? there r tons of channels like i care where i write aslong as i see a bot name in a channel i take my turn
aight
#bot-commands
!paste
ok i want to send randomized embeds each time as i have setup here but i don't know how i would do that code https://paste.pythondiscord.com/wapazanusu.py
put the embeds in an array and use the random.choice function from the random module
how would i set that up?
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
woah
you were lurking the whole time? xD
kindof , im mostly in the channel
oof, fair enough
ok so like this? https://paste.pythondiscord.com/ihunamipen.py
i don't really play zround with random choice
you put the embeds in a tuple
;-;
Nono
this is how random.choice works
!e ```py
import random ;
l = [1,2,3]
print(random.choice(l))
here i choosed numbers as the list , you may use embed objects```
lmao
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2
be nice if i could see what you typed
so , in the same way you can have ```py
my_list = [em1 , em2 , em3 ....]
the_random_embed = random.choice(my_list)
@echo wasp
this was the input
right ok
hm
don't forget to make this local
so i did do it right
no?
no i am thinking
smh
you dont define values inside the random.choice ```py
random.choice(em1 = ...)
it means you are providing a value for em1 in the choice method
another sidenote , dont use on_message events for making commands!
what sarthak said, choice doesn't have any em1 kwarg
function
method*
eh
?
nvm
lol i am trying to help someone out and it stumped me i don't want to redo there bot on them
my point
a plain def is a normal function , a def function inside a class is method
yeah yeah, I saw
I'm dumb
i feel you
dont redo it , but you can do it correctly further :)
welp
right
just call it a function
you wrote this the random_embed is the thing that gets sent right
if you wish to use random.choice directly for the embed kwarg , you wont use the random_embed var
let me clean this up and i'll show ya
!d discord.Message.add_reaction get the discord.Message object and then use this method
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
^
no idea, try asking in the disnake server
oof
snake server?
doesnt work π¦
hello
be patient, and it looks like all of disnake's good contributors are all offline
which part of it doesn't work?
show menu_callback
the emoji reaction
disnake, the message wasn't for you
show error
lol
confirm?
no error, just wont show the emoji
show your code
@Bot.command()
async def Poll(ctx, *, message, ):
embed=discord.Embed(title="Poll",description=f"{message}")
msg=await ctx.channel.send(embed=embed)
await msg.add_reaction('π')
await msg.add_reaction('π')
hey how the fuck is discord.ChannelType.news and a disnake error possible
language
!d disnake.ChannelType.news i dont see a issue with this
A guild news channel.
try using the unicode version π <=
uh...
ow
more info about unicode pls
no
they are strings, discord probably uses some markdown feature to make strings look like emojis
i havent been coding bots for like a day or something but im here because some people usually have python errors
for some reason-
huh?
you okay?
π€
no like usually people get a python issue, not a discord.py/disnake issue and i know basic python so im here to be here
and most people making discord bots encounter them
is the server a community one?
no comments
This is a #discord-bots channel. What did you expect?
python issues
lmao
yeah i used to be super active here though and i realized some people usually have errors but discord.py/disnake doesn't cause them, and i still thought that still happening so im here for some reason.
like for example SyntaxError is not what discord.py/disnake causes because i think they have custom errors i forgor
I lost 2 brain cells trying to read it and 4 to understand this

lol
Was your issue solved yet
nope π¦ can you help me, pls?
whats the issue? 
like I said, use unicode emojis
unicode where?
well then you can do that part at the last , and please dont use import disnake as discord instead you can install disnake with discord namespace in your venv
$python -m pip install disnake[discord]

@crystal cliff this
import disnake as discord
'''Totally not a bad way to use import'''
this is good?
how is doing that possible?
triggers me
so its '<the unicode>' ?
just copy this π
and paste it to where you used add_reaction
ok, will try it & let you know
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
oh sorry/
# voice.play(discord.FFmpegPCMAudio({song_id}.mp3))
voice.play(discord.FFmpegPCMAudio(f"/home/container/songs/{song_id}.mp3"))
with open("./downloaded_songs.json", "w") as f:
json.dump(downloaded, f)
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
else:
await ctx.send("I am not connected to a voice channel")
it dosent play the audio.
nothing in console
What's the issue
i was dumb, i didnt give it, add reactions perms π
??
its supposed to play a MP3 file, in a discord vc.
bot just jois and leaves
duh-
if voice.is_connected():
await voice.disconnect()```
but, why
this makes the bot disconnect
if voice.is_connected():
await voice.disconnect()```
You are skidding -,-
kek
Most prolly
;-;
also
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)```
is basically
`voice = ctx.voice_client`
oh k ty
show screenshot of code
@Bot.command()
async def Poll(ctx, *, message, ):
embed=discord.Embed(title="Poll",description=f"{message}")
msg=await ctx.channel.send(embed=embed)
await msg.add_reaction('π')
await msg.add_reaction('π ') {second emoji doesnt work}
can you send it in a pastebin
don't use emojis characters in your code, this is why:
!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.
^^
read
I fixed this now i can't figure out how to fix this
please use code blocks π
the commands won't work here ofc
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i mean , just msg.add_reaction(':+1:') will do the job
to_dict? you're trying that on an embed, right?
let me get you updated code https://paste.pythondiscord.com/vejemoheve.py
i think so i am helping someone and it confuses me
show full error
doesn't look like you are using tuples anywhere
- when asking for help, always show full error traceback, not just the line you think is showing the error
- also show all relevant code
- don't use screenshots
yes it in
it isn't
read the first line of the error
show error above the error you sent
there we go
kayle , is pincer bad?
Codeblocks?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
d.py server says it's bad, I just go along with it :^)
do you realize your beg command will always show the same embed? it won't "shuffle" every time you use the command
nope can ya fix it
which is why i said earlier to make the variable local
think about it
idk if he saw it or not
nope
why am I here? just to suffer?
probably
idk to help
looks pretty much of stealed code ( or atleast even names and command implementations ) from dpy
what's your native language?
that is what they told me to do it like that
nah, that's how you interpreted it
Lmao what
@commands.command()
async def send_dm(ctx,member: discord.Member, *, content):
me = await member.create_dm()
await me.send(content)```
**Error:** 'Context' object has no attribute 'create_dm'
**How to fix it?**
Gibberish :awkward:
bruh remove the commas at the end of statements where u define embeds
they did
await member.send() will send a dm
thanks
useless method call
!e ```py
var = 1,
print(type(var))
this is what u did
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'tuple'>
basically it becomes an tuple instead of embed
Using shim is actually worse than importing disnake as discord
I had brain damage from reading that
oh , may i know any reasons for that?
an -> a
can someone tell me why some tutorials say (ctx, *,
π i had an eye damage reading that
why is this star there this *?
i replaced tuple and embed in the edit but didnt change the article π
now try again ofc, you have to think for yourself sometimes too
that passes all the arguments into a parameter
eyes? who uses them anyways? tts be like
non it don't send an dm but it send an normal text in current channel
code? you probably implemented it wrong
@commands.command()
async def send_dm(ctx,member: discord.Member, *, content):
await member.send(content)```
here
how do i make this exeute after the song has finished playing
if voice.is_connected():
await voice.disconnect()
else:
await ctx.send("I am not connected to a voice channel")
you're in a class, use self as first parameter
Shim is less stable and less predictable
It emulates the package using different hacky techniques and that's not guaranteed to work as intended in each possible use case
In addition to that, it may incorrectly overwrite the discord.py library and cause some serious troubles
Agreed
You need self as the first argument
ok!
thanks @potent spear and @slate swan
5 bucks and we won't shame you
oh , i wasnt aware about the first part
tho i asked them to install it in a venv to avoid the discord.py lib overwrite ,
thanks for letting me know :) !
no shuffle
you miss f
that's because you have to do the random choice IN the beg function
have you learnt variable scoping
I learned quickscoping, same thing
ok
yes and no i listened not wrote
another brain cell lost for me
you asked
write it then if you listened?
You're welcome
If you want to decide whether to continue using the shim, you can have a look at the repo, it's public: https://github.com/DisnakeDev/discord-disnake
and i did define it above the command
yes
do you know what scope that is where you defined the variable?
pls start reading advice
so like so ctx.channel.send(random.choice(embed = begEM))
no
no.....use the choice method on the begEM var
that's it
they did that already
put the whole stinky begEM line IN your beg function
Really? If I remember correctly, yesterday I spent at least 30 minutes explaining views
Even though I have a final exam soon and other things to do
and the random amount of coins , how will you succeed with that thing if the embed variables are global?
this
ouch
use dark mode
I'm sure your brain productivity will be multiplied by 5
that's eye damage, I get (t)it
lol then i doze
ow ow
are we helping or teaching? cause this feels like teaching someone python basics π
i know python basics
doesnt seem so
I just hate these ()
face it and ace it, fren π
Can anyone give an example of emoji buttons with text?
parantheses
do you mean reactions as buttons? or buttons with an emoji as text/title of the button?
buttons with emoji as label
can't help you, I'm on v1.7.3
uh
!d discord.ui.button
supports emojis
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
view = View()
view.add_item(Button(emoji=emoji))```
others will
I do know that
I asked for an example
just passing an emoji kwarg does that..
just add an emoji parameter or do as Sarthak says
Oh ty
thats one way of making views too
other than the decorator method π
Didn't knew π
examples/views/button/link.py lines 18 to 28
class Google(disnake.ui.View):
def __init__(self, query: str):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f"https://www.google.com/search?q={query}"
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(disnake.ui.Button(label="Click Here", url=url))```
Cool
Dm me, Iβve just got this working
you are in a cog , add self as the first parameter
and no need to create_dm , just send the msg directly
Unfortunately there're only like 5 people that regularly help in disnake support server
Disnake isn't very popular (compared to pycord for example) so we have lack of support
Pycord was heavily advertised though
!d discord.User.create_dm
await create_dm()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`DMChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.DMChannel "discord.DMChannel") with this user.
This should be rarely called, as this is done transparently for most people.
should rarely be called
File "/home/container/main.py", line 359
return
TabError: inconsistent use of tabs and spaces in indentation
if voice.is_connected():
await voice.disconnect()
return <- line 359
whats wrong
That issue with popularity really affects a lot of stuff
Disnake is definitely not worse than pycord, at many aspects it's even better, but pycord was promoted by a youtuber so now it's way more popular than it should be
Very true
If they're outside of top-5 then probably yes
another add_reaction
Done that, the second emoji doesnβt work, invalid syntax
what do you think , will 3.1k of them survive
show code
well not all of them were forked to make a library
@Bot.command()
async def Poll(ctx, *, message, ):
embed=discord.Embed(title="Poll",description=f"{message}")
msg=await ctx.channel.send(embed=embed)
await msg.add_reaction('π')
await msg.add_reaction('π') the second doesnβt show
um like there are around 10 promising forks
atleast thats what i saw ppl using here
disnake , nextcord , pycord , e-dpy etc
and the error
Nothing on console, but underlined & says invalid syntax
there's no way to determine that since thats completely opinion based
i personally prefer disnake and nextcord over others
and as we just talked about libs like disnake didnt focus too much on promotions
so you cant actually make a top 5
hover on it , and see what it says
File "/home/container/main.py", line 358
await voice.disconnect()
From what I've heard, disnake is quite good
how do i fix this
here , disnake is preferred by most people
in discord.py server they'll just ask you to use no forks and hikari instead
nothing, but it still wont send
yea , its a library built from scratch
are u using replit
yes

@cedar smelt and its pretty faster and better with cache than dpy forks
and it provides you an option to either use raw hikari , or with some command handlers like lightbulb and tanjun
by command handler i mean , thing similar to discord.ext.commands
π
actual server? its annoying, when replit says package operation failed π¦
im cheap, i cant afford a vpn π¦
local host the bot until its ready to use
local?
flask
whats a frontend?
on your device
how do i make a website bot & link it?
Thatβs what I mean, the second part is hard π
π€
How can we disable all buttons by 1 click on 1 button?
you can make a function which disables all the View.children inside the view class , and call it upon the button_click
if you're using dpy master/any fork
To connect your bot to a website you need to make your own api.
But flask is sync code ;-;
tbf if you are looking to make a Discord bot with dashboard then just code your bot in node.js
Saves a lot of trouble.
anyone know how I can set up paginations for discord embeds?
If y'all could tell someone who was just starting out with coding discord bots something, what would you tell them?
ill ask them something instead π
did you learn python before falling into this trap?
to not use text files for storing data
usually people respond with "no" to this question π
what
yes that is true
ive seen new people try discord.py (haven't seen new people use forks yet) when they dk python π
Sadge
Itβs sickening to see people still use dpy and discord components
To get back in line.
thats nothing , ive seen ppl mixing discord.py and discord.js
aka me

!pypi discord.js
oh
Btw, do any of you know how to do paging with embeds?
Same
Why would you mix js and discord.py
This is honestly an insult.
π
Do you guys know what discord libraries I should use with discord.py? (I am curious cause, I have seen a lot of people talk about other python libraries)
i love hikari for solving all these issues
1 . doesnt run on replit
2 . is comparetively harder than dpy so no beginner would love that
you mean forks right
Ye
Hmm tbh I didn't use children....
what , any component inside the View is its children
replace dpy with nextcord or disnake
i recommend disnake, it's still being updated and it doesn't require you to use 3rd party libraries like discord components, discord slash or something like that
ive seen 1 person say it has best support for slash commands
it's better than d.py?
Other non forks like pincer and hikari are promising and have many extra features, so I would also look into those
Ohhh mb mb, I didn't know it. But how to check if some one clicked the button?
pincer looks like a dpy clone to me
hikari docs acc look kinda sexy https://www.hikari-py.dev/hikari/
Itβs from scratch
what library do u use
!pypi pincer
ik
am I the only one here who uses discord.py solely?
they are , but a bit hard to read
but it has other things like customizable middleware and static typing
Let's all go to hikari.
π³ tru
hikari docs are hard to read lmao
Pycord
I think I'll stick with discord.py for now
well , they documented everything existing in the library :) event the impl and http so its kinda complex
Yeah ik
btw, do any of you guys know how to add paginations in embeds?
!d nextcord.ext.commands.Paginator
class nextcord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')```
A class that aids in paginating code blocks for Discord messages.
len(x) Returns the total number of characters in the paginator.
how do you construct those buttons ```py
class Button(pycord.ui.Button):
...
or the decorator method ?
@pycord.ui.button(*args)
@lost vine
In nextcord?
do you know how to add them with dpy?
Around 3.1k
You canβt lmao thatβs why donβt use dpy

well you might be able to but you miss out on tons of other features
i wanna try hikari ngl
can I mix nextcord and discord.py by any chance?
hikari only channel now :3
um
Why would you do that.
what knowledge does hikari need in pyton
You have to uninstall discord to use nextcord
I use def, not class
All of my code is in discord.py
!d discord.ext.commands.Paginator
class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')```
A class that aids in paginating code blocks for Discord messages.
len(x) Returns the total number of characters in the paginator.
Itβs easy to migrate to nextcord
import nextcord as discord
same as discord.py
Just change all the imports to nextcord lmao
what
π€¨
It's that simple to change?-
all you need is to change the importa
just search replace it
and donβt use βas discordβ
okeh
How to migrate from discord.py to the maintained fork, Nextcord
β€ Subscribe: http://bit.ly/SubscribeDPT
In this tutorial, I will be discussing the closure of discord.py, the alternatives, and how to migrate your Python Discord bot from discord.py to nextcord.
π¨βπ» Source Code
https://github.com/DenverCoder1/Tutorial-Discord-Bot/tree/nextcord-m...
Just use CTRL + SHIFT + H
i have a chicken bone in my hand so i sucj at pselling
guys is hikari better than disnake btw
Small amount.
It got less support so you do need to code more.
idk but hikari needs another lib for commands iirc
eh
What's the thing for the image top right
ill stick to disnake
you mean a thumbnail image?
!d discord.Embed.author
property author: _EmbedAuthorProxy```
Returns an `EmbedProxy` denoting the author contents.
See [`set_author()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.set_author "discord.Embed.set_author") for possible values you can access.
If the attribute has no value then [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") is returned.
!d discord.Embed.thumbnail <==
property thumbnail: _EmbedMediaProxy```
Returns an `EmbedProxy` denoting the thumbnail contents.
Possible attributes you can access are...
uh idk
py-cord's namespace is still discord
class MyView(View):
async def disable_buttons(self):
for child in self.children:
child.disabled=True
# this disables all the buttons
# and then you can edit that message
# get the message using MyView().message = (the message view is used on)
await self.message.edit(view=self)
h
they haven't changed the folder name
i think putting long stuff into a function makes code readable
PEP8 π¬
π³
hikari & pincer > any fork
not related
file names must be always lower cased
its for the help command tho
you can do str.title()
uh guys i think i broke JetBrains system. my Rider trial was set to expire yesterday and i still have access LMAO
How do I write that in my code.
embed = add...
now it says it expires today
Lmao
π
!d discord.Emebd.set_thumbnail
idk what str.title() is
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
ok
makes the first letter of a string capitalized
and the cog name is derived from the class name or the name arg inside the cog class , not the file name
def load_extensions() -> None:
extensions = ["Moderation", "Customization", "Fun", "Other", "Image", "Staff"]
for ext in extensions:
bot.load_extension(ext)
what is -> None for
It returns nothing
shows that the function doesn't return anything
# Fun.py
# the file name is not the cog name
class MyCog(Cog , name='the cog name , the class name is registered as its name if this arg is not used'):
...
How to get DMs of people in channel
oh yeah and does this do the same as the for loop you did
it took me so long to get cogs to work when I first discovered them
omg thx
yea , is same
but why use a variable for it
what
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelβs hash.
str(x) Returns a string representation of the channel
there are literal examples on the d.py's documentation
Oh let me try
self.message isn't even a thing in the class
Ik I was stupid
did you even read the comments ?
I want to set duration, how do i make it with m, h, d
Time converter
load_extensions = lambda: [bot.load_extension(x) for x in ["Moderation", "Customization", "Fun", "Other", "Image", "Staff"]]
``` lmao
no
read the third one :p
aw thats hella complicatd
Is there docs or something?
π§
why would there be?
idk list comprehension
you derive from the commands.Converter but no
itβs mostly custom
!d discord.ext.commands.Converter
class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.
This allows you to implement converters that function similar to the special cased `discord` classes.
Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
subclass commands.Converter, typehint the argument to the TimeConverter
lmao thatβs exactly how I do mine
What argument?
the argument provided for command ig
Time argument
!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
in their case "duration"?
i saw lucas doing that π
Hmmm
also like
why are your parameters starting with capital letters
idk
@heavy folio bro, don't expect that if you subclass a class, and typehint something as the class it'll work
looks nice?
no ir doesnβt
discord.py converts typehinted arguments
it works for me lmao
of course
so it'll work?
holy shit the name parameter/argument/i forgor actually works no fuckign way
???
I have a custom TimeConverter class
(bot:=(commands:=__import__("importlib").import_module(".commands", "discord.ext")).Bot(command_prefix="!")) and (hi:=bot.command(name="hi")(__import__("asyncio").coroutine(lambda ctx:(await ctx.send("hello") for _ in '_').__anext__()))) and bot.run("")
point is?
which is why i said subclass commands.Converter, typehint to that
it does , since its an instance of commands.Converter
that's what he needs
^
yeah
i seriously want to use this so bad
thats not what I meant
but the readability is fucking like 0.5
π
I meant that if you do this ```py
class Class(commands.Converter):
...
async def func(ctx, param: Class)
``` and you do !func 5h it'll work. you'd actually need code to make this to work
Thatβs what I do lmao
blatantly subclassing something wont get what you want
But with code in the class
yeah? you can't expect it to appear out of no where lol
thats my point
ofcourse
i didn't say it will get him what he wants
!source mute
Temporarily mute a user for the given reason and duration.
i said typehinting the arg to the subclassed converter will work, a reason being converts typehinted args, another reason being the subclassed converter is an instance of commands.Converter
i did not say by subclassing Converter it will get you what you want
!source pypi
Provide information about a specific package from PyPI.
You know that #bot-commands exists, right?
!paste
Discord converter for time has this https://paste.pythondiscord.com/ireyomicom.py
Uhmm.. Discord related code!
Ok, I finished migrating to nextcord
how to make embed with buttons?
you cant do that, you can send a message with embed and buttons
anyways, are you on dpy?
or which lib
yeah
i want that
which lib
i use disnake
!d disnake.ui.View
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
wat
!d disnake.ui.Button
class disnake.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.
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 pass in a disnake.ui.View object into the view kwarg in send()
too much for you? check out examples in the github repo
hey i'm struggling to add a reaction to a message, but i can't, i need to add this original emoji π and i can't find the ID
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Hey how to get messages from user in DM channel of bot?
i can insert just the emoji?
!d discord.DMChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
mhm as a str/discord.Emoji object
i dont understand
Not talking to you lol
wait to what message
Phew
it returns an asynciterator, so ```py
async for m in channel.history(limit=100):
# do stuff
correct me if im wrong
!d discord.User.dm_channel returns a DMChannel object , where you can use .history
property dm_channel: Optional[DMChannel]```
Returns the channel associated with this user if it exists.
If this returns `None`, you can create a DM channel by calling the [`create_dm()`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.create_dm "discord.User.create_dm") coroutine function.
^
May i ask why you even need to previous sended messages from a dm?
why not
can u give me a github for an example :( I'm just start learn py
i already provided an example
discord bot is not a good beginner project
which project for starter?
something not a discord bot
tic tac toe in console
yea some consople app
But.. discord bot is also a console app ;-;
π€¨
Executes in a console right?
clever
:3
gotta abandon rider for vs 2022 ):
@slim ibex sooo... dsharp huh
Imagine dsharp+++ coming out
imagine c+++
Can't deny the 7nm+++++++++++ though
each plus adds 1 nm
π
cuz they can't seem to get under 14nm
i got 3700x
!ot exists
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Okay lets go there and I'll brag about my super computer
I run my Discord bot in 1440p so it doesn't really matter.
so uh who wants to make a discord api wrapper
π
Hunter
def getPlayerListEmbed(self):
try:
embed = discord.Embed(
title=self.name, description=f"**Server IP:** {self.address}:{self.port}\n**Total Players:** {self.players}", color=0xfbb92c, url=self.url)
except HTTPException:
embed = discord.Embed(
title=self.name, description=f"**Server IP:** {self.address}:{self.port}\n**Total Players:** {self.players}", color=0xfbb92c)
for index, playerList in enumerate(self.getFormattedPlayerList()):
embed.add_field(
name=f"Player List {index+1}", value=playerList, inline=False)
embed.set_footer(text="Note: Only 10 names are supported per list.")
return embed```
```py
@commands.command(help="List players in the servers.", aliases=['lp'])
async def listplayers(self, ctx: commands.Context, index: int):
try:
server = self.serverList[str(ctx.guild.id)][index-1]
except IndexError:
return await ctx.send(f"There is no index `{index}` in my storage.")
except KeyError:
return await ctx.send("`No servers have been added for this guild.`")
sampinfo = SAMPInfo(server['address'], server['port'])
if not(sampinfo.connected):
return await ctx.send(f"Looks like the server is not online right now.\nIf the server is online on your side, please use `{self.bot.command_prefix}reportissue` for us to fix the issue.")
playerlist_embed = sampinfo.getPlayerListEmbed()
playerlist_embed.set_author(
name="MecHaNiC SA-MP Info", icon_url=self.bot.user.avatar_url)
await ctx.send(embed=playerlist_embed)```
In embed.url: Not a well formed URL.
whats wrong?
i did gave it an exception response
nope
They can but your bot can't be over 10 servers.
how
!d disnake.ext.commands.Bot.create_guild
await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild").
Bot accounts in more than 10 guilds are not allowed to create guilds.
You got the full traceback?
File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "D:\Discord Bot\GitHub\asdf\cogs\samp.py", line 197, in listplayers
await ctx.send(embed=playerlist_embed)
File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.url: Not a well formed URL.
You are excepting HTTPException in the try except block and it raises the http error and stops the program
Well no he gets it on the .send()
oh
File "D:\Discord Bot\GitHub\asdf\cogs\samp.py", line 197, in listplayers
await ctx.send(embed=playerlist_embed)`
What library are you using?
can you set an embed to a function like he did?
can u ping someone in like a embed title
yes
no
it'll show as <@userID>; it won't be embedded/show as pinged
What does self.bot.user.avatar_url return?
the bot avatar
Could you confirm?
yes
Cause as for as i see there aren't any other URL's
show playerlist_embed
It does work?
Yeah prob self.url dunno what that is.
Best to check if it is defined or not than an exception.
Since it doesn't raise the exception there, it only gives an error when you try to send it.
yeah
invalid form body
how can i?
means usaly ur embed is fucked
like if u try put url for icon or stuffs but url not found i think
if statement.
No usually if None is passed or if it isn't an url format.
?
nvrm just check url with if statement
how do we write for invalid formats?
Check if it is true
if url:
...
def getPlayerListEmbed(self):
if self.url is True:
embed = discord.Embed(
title=self.name, description=f"**Server IP:** {self.address}:{self.port}\n**Total Players:** {self.players}", color=0xfbb92c, url=self.url)
else:
embed = discord.Embed(
title=self.name, description=f"**Server IP:** {self.address}:{self.port}\n**Total Players:** {self.players}", color=0xfbb92c) ```
okay?
ye
if self.url:
what does f stand for? like in "description=f"....
format i think
they are f strings
the error is back
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embed.url: Not a well formed URL.
thats .format()
its so u can use variable in {} brackets
hmm
ah fstrings
aka format-strings
@quick gust try .. if self.url != "":
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
it will check if url is empty string
@honest vesseldid you meant me to try it?
ye
well same error still occurs
print(self.url) n look at it
was talking about the ping
https://coming soon!
well there u have issue
that i already told :3
it makes u think an url is always set
then u might need to have regexp to check if valid url aka domain.tdl
how do i do that?
stuff like this
urls doesnt have spaces
@cloud dawn urls does but not domains
ik. i am trying if the url is a vlaid one, it sends one msg and if the url is not a valid one it doesnt embed the url thing
urls don't have spaces.
since that is an invalid url it should just not send the url in the title
@waxen granite anotherway can be grab the error n respond with telling em they need a valid url or blank
i could but what i want to remove the url if its a n invalid one and dont embed it.
like this
do you know what regex is?
also, the only thing you have to add if it's a valid URL is embed.url = self.url
you don't have to recreate the whole embed again lol
^
you have 2 things to do when checking a url
- if it's valid (can be done via regex)
- try a simple request to it, if the response code is something in 2xx (like 204 or whatever), then you know the url is actually accessible
Successful responses go from ( 200 β 299 )
nope
like check for url only?
google it, this will be your way of checking if the url is valid
@potent spear if use requests it can be used to fish his bot ip
so regex prob best
just find someones regex pattern to use
in worst case scenario, that's true
this is the regex for a VALID link
URL_REG = re.compile(r'https?://(?:www\.)?.+')
if you know how to work with regex, you know what to do with this info
thats prob enough for him
not optimal for better accurate
and wat if http://hi.kkkkkkk
or google.com
that's not a link
My browser says it's pretty valid.
anyways, which websites would anyone link that aren't secure?
that would allow more shapes, http https or only www. or only google.com
url_regex = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
like, if it's http:// I'd think it could be sus
@potent spear its samp servers prob old or run by noobs
http://google.com/ is pretty sus yeah
get vaccinated nice one google
you just edited that link, if you copy, it wouldn't say http
No i typed that
no-one types a link lol
:(
old websites can still use http
yeah, we don't know why he needs it, so idk what to do with http or https
or small community pages like gameserver n admin not so technical in setup https
Some sites don't even need an https connection it's just marketing.
yo how do i add a category and description to my command @bot.command(aliases=["es"])
well thats wat https was made for
Cog or group?
@bot.command(aliases=["es"], description="tes")
nword
Let's keep it appropriate here.
in ur ctx.reply
kk
sorry
so how can i add the category
@cloud dawn
its group
you mean group?
its not cogs
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
eh?
.
u mostly want name, description, aliases
the group is a category
ok im back
u can add sub commands to it
so @bot.command(group="General")
why cant i use discord_buttons import?
Don't just make up kwargs
..
Did you install it?
name will automatically be the base.
yeah
kk
do i need to use .format to compare the self.url and regex?
im so disapointed that it doesnt work
no
@bot.command(aliases=["es"], description="Edit Snipes a message", usage=f"{prefix}editsnipe", group="General")
regex returns a list of potentially found urls, so it is empty don't include it.
bruh
You can't just use an f-string inside a kwarg.
so url=url_regex?
oh yh i forgor
No you gotta check it it contains an url then index out the url so it represents a string.
confusing :3
how do i make it not display that es
@bot.command(aliases=["es"], description="Edit Snipes a message", usage="editsnipe", group="General")
?how do i make it not show es .. ?
!d discord.ext.commands.Command.aliases
The list of aliases the command can be invoked under.
Is this the default help cmd?
how to create embeds that has buttons on the bottom
!d disnake.ui.View
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Um... I think Discord just temporarily banned my bot. Does anyone know how long this lasts?
@cloud dawn
url_regex = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+") url1 = url_regex.search(self.url)
like this?
Depends on what you did
replit
I had written a purge command recently. Could this have been the reason?
ok im back
yh
try kill 1 in terminal
depends, could be like 2hrs sometimes, not too long I'd say
you could figure out WHY meanwhile
Yep.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embed.url: Scheme "<re.match object; span=(0, 19), match='https" is not supported. Scheme must be one of ('http', 'https').
@commands.has_permissions(administrator=True)
@commands.command(name='purge', help='Deletes a specific number of messages')
async def purge(self, ctx, number: int):
await ctx.channel.purge(limit=number)
You are sending the regex object
Is this malicious code?
@cloud dawn did u know there's a cooldown kwarg in command deco now?
wdym?
yh
didn't work
are you sure this is it?
url1 = url_regex.search(self.url).group(0)
In disnake?
!d disnake.ext.commands.Command
class disnake.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
ah well , replit uses shared ips , so you can get temp ip banned even if it was someone else
There was a print function below it, but that can't be it.
So now we can do
basic_cd = commands.CooldownMapping...
@bot.command(cooldown=basic_cd)
async def cmd(ctx):
. . .
@bot.command(cooldown=basic_cd)
async def cmd2(ctx):
. . .
discord.py 2.0
:3
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
back to square 1 :3
In embed.url: Not a well formed URL.```
check other code too, like infinite loops or tasks or whatever
Sarthak betrayed me 
π when did i do that
"hikari lover"
Please debug the command, these error don't really give any information.
U need to add https:// in front of the URL
Like https://google.com, not google.com
π cause its hot
||so are you||

i mean , check the cache impl
I didn't make a lot of changes recently. Especially none involving infinite loops...
maybe not obvious to you...
check whereever you make API calls, those are the suckers
Ik dpy forks suck but why :pleadingCry:
that's why people have cooldowns etc
am straight
lies
Nou
π agrees (im excluding disnake )
more like im being codefeeded by lucas' hikari tutorials
so am moving to it
why are you watching Lucas
I'm okay with it if it's only gonna last for a few hours tbh...
I've reverted to my second last commit.
Isn't hikari bascially almost the same layout.
No
Just make sure people can't spam API intensive commands
Itβs definitely not
its completely different
Hikari lacks all the abstractions that dpy has..
all okay. nothing in debug
Much better naming imo
Do you mean the commands which use some API other than Discord?
..?
What's good about hikari?
nah, more the api calls to discord that users can access
make sure people can't abuse those
I'm implying to printing data.
You.... betrayed me again 
i ran the debug in vsc
Internals π₯Ί
Ok, I'll try adding a cooldown
π nuuu , was kidding
Itβs not that good. Being able to ban someone by name and discriminator is a security flaw
i was~
um
not for every command ofc (not per se), just like the ones you might think
also don't add cooldown for special admin commands or whatever, most people with admin rights have brains
He was joking lol
