#discord-bots
1 messages ยท Page 638 of 1
discord.py don't have slash commands
hai kayle ๐
oh. disappointing
can someone help me
I would suggest u to move to a fork like disnake or something
Or Discord.py 2.0
aight
async def send_cog_help(self, cog):
coge = self.context.bot.get_cog(str(cog).title())
title = coge.qualified_name or "No"
await self.send_help_embed(
f"{title} Category", coge.description, coge.get_commands()
)
``` but I'm getting a `NoneType` issue though at `coge`
For 40 y/o's
oh
lmaoo
coge
What
lol
"coge" ๐ญ
Cz u don't have a cog with that name
What's wrong with my variable naming
Facts
Nothing
!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.
coge sounds like a bad version of code or cogs
it exists, my help command says so
or doge
cant argue
from discord import Client, Intents, Embed
from discord_slash import SlashCommand, SlashContext
bot = Client(intents=Intents.default())
slash = SlashCommand(bot)
@slash.slash(name="test")
async def test(ctx: SlashContext):
embed = Embed(title="Embed Test")
await ctx.send(embed=embed)
bot.run("discord_token")
@maiden fable ? slash commands on d.py
wtf
Ah that lib. Never used that sorry
discord-slash sucks, doesnt even work properly
(:
it's recommended to use a fork of dpy, and that should work lol
disnake ๐
Try printing cog.title()
hunter
Hm?
why is your pfp so cheerful
Idk ngl
Damn almost 23k messages in this channel alone ๐
async def send_cog_help(self, cog):
coge = self.context.bot.get_cog(str(cog).title())
print(cog)
print(str(cog).title())
print(coge)
``` ^^^
"only"
Eh, I'm getting to about 11k
Ah, then Cog is the cog object
I need to learn cogs
wtf even are cogs
How do i make an embed underline a message?
errr
the function will never be called until the HelpCommand object recognises that its a cog
And only 41k in total
huh?
__text__
that's ....cursed lmao
hi
Most of them are useless ngl ๐คทโโ๏ธ
ive got no messagess
Underline?
lmaoo
oh NSFW but yeah
if this is what you call underlining then yes
๐
I am gonna accept the rules even when I ain't 18, dw
lmaooo
thats what most people do
I have also done that ngl
everywhere
ayo wtf
That time I was actually 15 ๐คฃ
i cannot acess nsfw channel bcoz I entered my real age which was under 16 lol
U talking about me? Yea
best of luck
didnt check recently
same lmao
I didn't know discord was for above 13 so I input a fake age ๐คทโโ๏ธ
Yea I know
i put it even higher than my elder brother's age ,-,
lol xd
!ot if u wanna continue
Off-topic channels
There are three off-topic channels:
โข #ot2-never-nesterโs-nightmare
โข #ot1-perplexing-regexing
โข #ot0-psvmโs-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
you guys epic
hunter what have you done
but is it a cog though
why not
How does it not recognize it's a cog? Is it because of the casting i did?
Many. Fucked. Up. Things.
Anyways #ot0-psvmโs-eternal-disapproval if u wanna continue. This is a topical chat
if ctx.author == 493451846543998977:
await ctx.send("!ot")
๐
!ot
`!ot
O
.!ot
^^
I needed an nsfw channel to make my insulting bot work ๐
ok
i my code still aint finished
but who cares
it doesn't work anyways
I won't be surprised if a mod comes here and warns us all ๐
async def command_callback(self, ctx, *, command=None):
await self.prepare_help_command(ctx, command)
bot = ctx.bot
if command is None:
mapping = self.get_bot_mapping()
return await self.send_bot_help(mapping)
# Check if it's a cog
cog = bot.get_cog(command)
if cog is not None:
return await self.send_cog_help(cog)
when you use your help command , this function is called before everything , the first phase checks if its a command , and as you can see its using cog = bot.get_cog(command) , and your command variable is not in the same case as the cog , it does not call the send_cog_help function , hope i was clear
Lol
But why doesn't it call the send_cog_help function
for example your cog is registered with the name CoG , and you do Cog , the command variable would be "Cog" , and bot.get_cog('Cog) would return None , so the function wont be called
Is there a way to backup a server instead of using templates?
yes its complex tho
Xenon bot?
I want to make my own
Literally don't understand what you mean by that, give me a tldr
case sensitive., CoG <> Cog
print = warn
Huh?
What does <> mean
mean bigger and smaller
ok so bot.get_cog() is case sensitive , which means if your cog is registered with name CogName , bot.get_cog('cogname') would return None
is this clear?
CoG is bigger and smaller than Cog?
No its code
I don't know that what my math teacher said
He just meant they ain't equal
still searching for sarcasm
Very clear
Ok good luck
You forgot a line its Clean
cog = bot.get_cog(command)
if cog is not None:
return await self.send_cog_help(cog)```
so do you not except the help command to call the `send_cog_help` function now , right?
I guess
thats what i meant , and if you change the command to command.lower() and the cog names to lower , it the help command becomes case insensitive
as in that case , the arg sent with help command would always be lower , and so are your cog names
hm
async def command(ctx, input:string): and then subclass string, the parent class being str. You just make it all lower
who's this for
!e py class string(str): def __str__(self): return self.lower() def x(text:string): print(string(text)) x("HELLO")
aw
that isn't lower
really?
!d str.lower
str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.
The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
go to the library files , ext/commands/help.py , look for py async def command_callback(self, ctx, *, command=None) and inside it do the change which i said
you said don't make change in the internals though
i said its not recommended
Aight
aight
unless you know what you are doing :p
I don't
well , it wont break anything
so what ur saying is i should look for a command named that if not find a cog with that name?
the function first checks if its a command , if it aint it checks its a cog
so I should do that?
yea just change line 839 from py cog = bot.get_cog(command) to py cog = bot.get_cog(command.lower())
what format does message.created_at return?
datetime.datetime object
and the same for embed.timestamp?
okay thanks
datetime.datetime or Embed.Empty object
@slate swan guide me more please, this is my code
async def send_cog_help(self, cog):
the_cog_name = cog.qualified_name.title()
the_new_cog = self.context.bot.get_cog(the_cog_name)
if the_new_cog is not None:
title = the_new_cog.qualified_name or "No"
await self.send_help_embed(
f"{title} Category", the_new_cog.description, the_new_cog.get_commands()
)
``` how would I check if it isnt a command tho
the 3rd line is unnecessary
Which
the_new_cog
why not
the cog variable is already a Cog object , so you dont need to get it
^
but i wanna convert it into a string then a cog back
Covert to what
That doesnโt change the value of cog param.
did you do what i said , kayle?
not really I didn't understand
as i explained earlier , your send_cog_help function wont be executed until the cog exists....
so doing any changes inside your send_cog_help wont fetch the cog
same capitalisation
Get the cog in on_help_command_error
or just try what i told
I don't have that, it's kinda useless
wut capitalistation
I get this error "discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression" But the command still does what it's suppost to
That's a way i could think of to get a cog with lowercase str
something is none
๐คฆ what's so confusing in this ,
rename all your cogs in lower case
change line 839 from
py cog = bot.get_cog(command)topy cog = bot.get_cog(command.lower())
In discord/ext/commands/help.py
and your code is?....
not for you
bruh 
but i dont wanna make my cogs to lower case? or do you mean that in the code
is that a clown or what
wait how do i change something in the files though
your saying I should change something in discord/ext/commands/help.py
open python path , site-packages -> discord library
but I dont wanna edit the internal files
is there someway else I could do what I want
there's a easy way , but is kinda weird
alright
are your cogs all in same capitalisation type?
like the first letter is capital for all and others in lower case
yes
PEP8 recommends capital class names
you get a error like No command called {0} found. when you try to get help for cog in different case right?
Hi
Yes, I do.
so as sherlock said you can use the on_help_command_error thing , and check if the error is an instance of command_not_found
hm
the error is a string so you need to somehow get the command name from the string
Iโll take that as a yes
command?
!d discord.ext.commands.HelpCommand.on_help_command_error
await on_help_command_error(ctx, error)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The help commandโs error handler, as specified by [Error Handling](https://discordpy.readthedocs.io/en/master/ext/commands/commands.html#ext-commands-error-handler).
Useful to override if you need some specific behaviour when the error handler is called.
By default this method does nothing and just propagates to the default error handlers.
cog*
and you can use bot.get_cog(<the cog name you got in error>.title()
since you have all cog names like first character as upper , and others lower , .title would work
and call send_cog_help from there
hm
how would I access something local though
async def on_help_command_error(self, ctx, error):
cog = self.bot.get_cog(ctx.command.name)
the_cog = cog
async def send_cog_help(self, ctx, cog):
...
can some1 help???
Already
send the code?
but like why?
thats wrong, no?
lmao
its discord.ext not .py
You know what I mean
do other client.command()s work fine?
no
i accidentally deleted all the imports
and it happened
so
๐
AttributeError: 'Client' object has no attribute 'command'
What
you see, have imported commands not command
do this,
from discord.ext.commands import command
from discord.ext import command
no......
@rocky mist
๐ญ I donโt have my pc
?
oops
import that
has discord py done something
its not
No? You can import stuff like that
its not what?
I do that and it work
Huh
it's commands
Iโll have to ask my dad
duude
Nice troller
^^^
๐wtf
your a troll
brooooo
๐
this guy has two discord.ext.commands
Remove discord.Client variable

@quick gust is good guy
fs
He wonโt troll like me
ffs, why did u remove ur first one.......
What does fs mean
ffs*
just do this man for god's sake,
from discord.ext.commands import command```
for fuck sake
Sweet
Iโm just going to watch this
i know im dumb so ok?
Did he declare client twice?
sarthak is here he'll help
not like this , error you be a string like No command called "cogname" found , you need to filter the cogname out of string , and use ```py
cog = self.bot.get_cog(<the string you filtered)
it may not be a cog
if cog:
await self.send_cog_help(ctx,cog)```
Oh
Infernum please correct me
yeah i think
@rocky mist
AttributeError: 'Client' object has no attribute 'command'
aight
Thank infernum
Client cannot have commands
Use Bot instead
With Client you are limited to events and similar
See the difference here:
So you need
bot = commands.Bot(...)
instead of
client = Client(...)
At the top of your file
Where'd you get that image
@slate swan Can I put on_help_command_error anywhere? Does it work with subclassed help commands?
it works inside it
show code
i put it in my bot class if thats ok
nu , its a method of HelpCommand object
hm
aight br
@slate swan doesn't change
async def on_help_command_error(ctx, error):
await ctx.send("no")
``` ^^^
wait i missed self
oops
Wait, it still doesn't work if I put self inside
:(
did you change the help_command= paramter to your HelpCommand class , since it seems to be like the default one
yes
you sure its contained inside the HelpCommand class?
helllllo how to make the bot mobile status
you cant
em okkk thanks
how do I add this feature in my discord bot?
this comes whenever you click on the discord bot profile
go to developer portal
go to url or something mess around with it and it should pop up
I think you could but it was a bug
yeah im certain
oh
my class looks like this
class HelpCommand(...):
def __init__(self):
...
async def on_help_command_error(ctx, error):
...
```^^^
How to get the Add to server button to your bot's profile:
- Go to https://discord.com/developers/applications/ and select your bot.
- From the side menu click on Oauth2 -> General
- Modify the Default Authorization Link section with a Custom URL or In-App authorization
Article: https://discord.com/blog/discord-bots-and-app-discovery-announcement
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
oh
thank you!!
can someone show me an example of how to list all people with a specific role
hello?
this could help
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
essentially u need to make use of ctx.message.server.members and if role in <current-member>.roles
no need to do that , just role.members would be enough.
ah
and ctx.message.server aint a thing ,its guild
right it changed to guild
ctx.guild.members would give you the members of a guild/server and u can iterate through it like for each_member in ctx.guild.members and see if each_member.roles matches ur role?
That is really inefficient compared to just using specific_role.members
Granted that specific_role is a discord.Role object
ah, i didnt know that
How's lefi going on?
so ctx.guild.roles?

Guild.roles would be a list of all roles
You want what Sarthak said
hi
Lefi is going good, very promising. I'm still doing documentation though
Hey, is it possible to make something like typing.Optional with custom converter where it passes the value to the next arg if the value type isn't the type given?
You mean the most boring part?
oooh https://github.com/an-dyy/Lefi this urs?
Yea it is
And yes its the most boring part
I can't do anything cool till I finish docs
what does it do
smthn like pprint?
Its a discord API wrapper
Python 2 syntax ๐ค
!resources and also #python-discussion for casual talking
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ohh
a
sure

It is rich
so, I have
class Literal(Converter):
"""A class for custom Literal"""
values: tuple[str, ...] | str
def __class_getitem__(cls, item):
self = cls()
self.values = item
return self
async def convert(self, ctx, argument):
"""Converts the argument to any of the exact value given"""
if argument in self.values:
return argument
raise UnexpectedArgument(f"\"{argument}\" is not a valid argument. "
f"Possible argument(s): {', '.join(self.values)}")
```this thing here, so the problem is that I want to make this as a merge of `typing.Literal` and `typing.Optional`. But the problem is `ctx.args` returns an uncomplete list. Due to the fact that the args isn't processed yet. How to implement `typing.Optional` here though?
ctx.args returning an incomplete list? 
I am dumber than u ngl
yes
If your gonna be implementing these custom types it would be a lot easier to override the discord.py's string parser
You can do this through get_context afaik
which string parser?
You mean the part where dpy gets args from the message?
View iirc its called holdon
This is created along with Context
And it handles arg parsing
If you override this with your own class or subclass this
You can set an instance var for the last arg
If its not isinstance
Wait, wtf is even this ๐ญ
And replace the next, by changing index
Just some over the top tokenizer
I have one for lefi but its a lot more compact
O, gonna read your source so that I don't lose my sanity
will try
and where should I pass the class?
I'll have to check the source code but iirc its in get_context?
your string parser is much neater than dpy's ngl
discord/ext/commands/bot.py line 934
view = StringView(message.content)```
Yea it is in get_context
So what's the use of this parser?
wait... so I need to override the whole get_context and not calling super?
It parses args from a string
(I know I am dumb)
Me who achieved that in 7 lines: ๐
Yea, because you need to override which parser, or you can just create a new class then manually set it on context
okay it's much complicated than i thought
Well, I doubt 7 lines could really handle all the pos and kwarg only parsing
It does ngl
oh, anyways will subclassing Greedy do something?
is anyone in here a good bot developer?
Really? I'd like to see that implementation if there is one
I get the message content, zips the args and kwargs from the message and I just pass those to the function
No clue
i mean discord bots
will try 1 sec
Everyone is
ok
How exactly are you ziping the args and kwargs from the message though?
I ain't on my lappy rn, gonna ping u once I get on it
It's a hackery implementation but since it's a private wrapper/code, I don't really care haha
......?
Just send a screenshot of the code from the repo if there is one then
Either way I think you have to use iteration and inspect.signature
I ain't got one tbh
Compare it with the list of arguments
Yea, I use slicing
i wrote in general what we need
really not a good idea
I use func.__code__ to get the number of args
Bro I told u before also, #โ๏ฝhow-to-get-help
Ik it's a bad implementation, but ๐คทโโ๏ธ
they used generic types while I'm using normal Converter which... won't work
So you get co_argcount and co_kwonlyargcount and compare it with a list of tokens being the raw strings of the message?
Well I just split the message content by spaces, slice the list with co_argcount and the content which is left after slicing is passed to the kwarg
umm, https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/converter.py#L993-L994 where does __origin__ and __args__ come from?
discord/ext/commands/converter.py lines 993 to 994
origin = getattr(converter, '__origin__', None)
args = getattr(converter, '__args__', ())```
Okay okay calm down, sorry
Alright yea, that makes sense to me I guess. That's basically what I'm doing right now in my string parser except mine has to worry about type annotations
Ah that's the problem. I ain't converting to the type hinted type, I am passing raw strings
Anyone? ^^
!e ```py
import typing; print(typing.Optional[str].args)
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
(<class 'str'>, <class 'NoneType'>)
^^
actually, ig https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/ext/commands/core.py#L580 this might work
discord/ext/commands/core.py line 580
async def _transform_greedy_pos(self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any) -> Any:```
why is everybody making a wrapper smh
I'm just a casual bot coder 
Lmao
I meant andy ofc
Can anyone help me now?
My on_help_command_error isn't working for some reason...
It keeps getting replaced with this instead of my on_help_command_error
I think that's triggered whenever there's an error in sending like lacking perms
No?
it's for the help command
When u do the help command but an error in sending the help embed
yeah
!d discord.ext.commands.HelpCommand.on_help_command_error
await on_help_command_error(ctx, error)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The help commandโs error handler, as specified by [Error Handling](https://discordpy.readthedocs.io/en/master/ext/commands/commands.html#ext-commands-error-handler).
Useful to override if you need some specific behaviour when the error handler is called.
By default this method does nothing and just propagates to the default error handlers.
but how does the bot not have permissions
it has admin
Bro
What
kayle man stuck with the help thingy ๐
I am telling u when that function will be called. it will be called when the bot won't have send message perms in the channel, for example
btw kayle , any reason for you to not name cogs in lower case?
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
โข PEP 8 document
โข Our PEP 8 song! :notes:
๐
bruh
ofc I did
it takes a name kwarg too
I wanna make my cogs case sensitive
Will that also work?
Yea...
class Mycog(commands.Cog , name = 'my cog name')```
ofc
Like if the class name was cog but the name was Cog and we did cog would the command work
Following pep8 correctly it would actually be MyCog
that was just a quick implementation example for name kwarg ,yeah
this
you mean py class cog(Cog , name='Cog'):?
it will get registered as Cog so only that will work
name would set the Cog object's name attr to Cog, but the class itself would still be cog
It wouldn't work in native python as it would say Cog is undefined while using cog
It only works in discord.py where it finds a Cog by the name, cog
but the bot.get_cog() function would get the cog when "cog" would be supplied to it , right?
yea
No only Cog as it was the name passed
oh yea , sorry i said the opposite
can you now try to do the thing i asked earlier? with the names lower cased..
rename all your cogs in lower case
change line 839 from
py cog = bot.get_cog(command)topy cog = bot.get_cog(command.lower())
In discord/ext/commands/help.py
datetime.datetime.utcnow
!d datetime.datetime.utcnow <=
classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.
This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now").
Warning
Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
\t <- what's this for
Ah i see
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
001 | def h:
002 | print(1)
003 | print(2)
Thx
can someone tell me how i make a bot that detects how much a user has clicked a button? like if a button has been sent 5 times and its the same button and a user clicked it 3 times and another use clicked it 2 times how do i make the bot show the total amount each of the user have clicked it?
make a dict, handle the callback, the key would be the id
if the key doesnt exist, set it to 0
can u show me a code example?
i wrote smth similar to this yesterday, not exactly what you want but should help
i dont think it will help, gotta give some new example wait
d = {}
def callback(author):
if author in d:
d[author] += 1
else:
d[author] = 0
smth like this
you understood?
the dict then will contain all the users with how many times they clicked as the value
d[author] += 1
if that doesnt work,
d[author] = d[author] + 1 should work
is it supposed to look something like this?
im kinda new to coding so i dont really know alot of stuff
well thats not gonna work just by copy pasting the entire thing and hoping it to work
button_callback
the name says it all
the dict has to be an attribute of your discord.ui.View subclass
as in my code, while initializing it should be an empty dict
im not going to explain that much because you are not supposed to be making discord bots until you know enough about python and OOP to understand what im currently saying
okay
consider learning about classes, OOP and decorators (spend atleast 2 weeks practicing these)
you kinda sus mr myxi
: |
do you have your own discord sever
no, why you asking tho
s
collections.Counter would help with this
!d collections.Counter
class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.
Elements are counted from an *iterable* or initialized from another *mapping* (or counter):
```py
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
tbh i skipped that thing when i was checking the docs of collections
myxi do you have a nice pfp to use
Imagine not using the default profile picture
dont like that thing anymore, discord made it shit
it isn't shit
The current one
compare it with the old one
yes
what old one
Lol
discord redesigned their logo some time ago
I honestly didn't realize it'd changed and I've been using this for a solid 5 months
this?
No
check the discord icon from 2017 or 2019
look how shit the new one looks
Yes
: |
Maybe if you use it for a long time you will get the difference
I want to do send.user
lol
to send the person using the bot a dm message
the member will not be identifiable
ctx.author.send("message") to send it to author
Thanks alot
np
Use a try and except
Depends if the author has dms on but that too
await it
Await it
okay to sek
Bro
I'm fast
Me too
I nearly made a succesfull copy of defcon but it fked up
๐ญ
just atleast 1 error that I have not yet figured out ;-;
Whats defcon
Send me it ๐ง
!src defcon
Check the DEFCON status or run a subcommand.
the error or code?
error
What's defcon?
may I explain it in the help channel?
Sure, ig
Python Defense Mechanism
๐จ
Cool
pls
Can't really help you without problem ngl
figure it out yoursel-nah, just kidding
you won't kill me if I reveal the fact that I'm using json as a db?
๐ฆ
Nah I am also the same
ok
when I do ;use laptop it says you don't own this item!
it's from the big first if statement
when I do ;use phone it completely ignores me
kk ty
Python so weird
!e
import asyncio
async def main():
await function()
async def function():
print("Hi")
asyncio.run(main())
hm
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
Hi
why is my exec code not sending its just printing it in terminal and not sending the results
send it then?
bet
just sends None in a embed but the error embed works
@bot.command()
async def val(ctx,*,code: str):
try:
vercode = code.strip("```").replace("py","",1)
embed0 = disnake.Embed(title="Terminal",description=exec(vercode))
await ctx.send(embed=embed0)
except Exception as error:
embed1 = disnake.Embed(title="Terminal",description=error)
await ctx.send(embed=embed1)
cant send it as a code block lmao
hm
well
assign something to exec() function
and then use that var inside description
ill try
as expected still sends None
show code
alr
only thing i changed
executation = exec(vercode)
embed0 = disnake.Embed(title="Terminal",description=executation)
hm
yah
๐
still dont know why it doesnt work
umm hello so im doing custom help
and i wanna like ?help class
so how i put the name and async def
u talk to who?
you
like this
i made a spotify command and it doesnt work for me
me: !help
bot: something...
show full code
from discord import Spotify
@client.command()
async def spotify(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
pass
if user.activities:
for activity in user.activities:
if isinstance(activity, Spotify):
embed = discord.Embed(
title = f"{user.name}'s Spotify",
description = "Listening to {}".format(activity.title),
color = 0xC902FF)
embed.set_thumbnail(url=activity.album_cover_url)
embed.add_field(name="Artist", value=activity.artist)
embed.add_field(name="Album", value=activity.album)
await ctx.send(embed=embed)
nothing
ok
nothing in the main console aswell
maybe user.activities is False
make an else statement
and await ctx.send("nothing")
didnt work
what does it send?
nthing
the word nothing?
should be a return
how to set embed value as none?
which value?
embed.add_field(name="?help class for classed command help", value=None, inline=False)
returned that
because, exec doesn't return the expression's value. what you're looking for is eval() however it will work only for one expression not multiple lines of code or statements
!e print(eval("1+5"))
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
6
Thats the thing eval wont work as its just lines and not a complicated code block
It does print but sends a result of None in a embed
i already sent a working snippet some time ago i think
I want to do it myself g
No no it works it just doesnt sends a result but sends a error but when it works it only prints it in the vsc terminal
Still confused about lambda lmao
what was the code
okie tq
@bot.command()
async def val(ctx,*,code: str):
try:
vercode = code.strip("```").replace("py","",1)
executation = exec(vercode)
embed1 = disnake.Embed(title="Terminal",description=executation)
await ctx.send(embed=embed1)
except Exception as error:
embed2 = disnake.Embed(title="Terminal",description=error)
await ctx.send(embed=embed2)
what was the code you passed to it
cant send it as a code block as it will be half one
elaborate
value of code arg
what was your expectation
to send the results as a embed but it just sends None
exec executed the code you passed to it
it will not return anything unless you do something i showed some while ago
what you did was calling the print statement
and it did it
!e
print("bot is running.")
exec("print('works')")```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
001 | bot is running.
002 | works
thats basically what you did
i see
!e
print(eval("'hello'"))```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
hello
because "hello" is an expression, eval will return the value of an expression
why
This makes me have a stroke๐
why tho
Math broke my brain so im having strokes now๐
you can assign the value of the global variable to a local variable of the function then delete the global one with del keyword if thats the problem
:/
No it wasnt ๐
i didnt even do any kind of maths there tho
Ik im taking classes and algebra broke my brain :#
Yes it is
but why you blaming my code cuz of it ๐
Cause freecodecamp does it better
๐
bruh
Didnt mean to offend you๐
i mean yeah there could be some other pro solutions like coding your own python interpreter to make it work but i thought thats gonna be easier
No that's a better idea
Source code: Lib/code.py
The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.
great
Yup
๐จ
defcon be still broken ;-;
Good luck writing the ast, lexer, tokenizer for that
My cog-case insensitive thing still broken ๐จ
Dont need it
i think you should use code i think it will work great for it
No need look at my process;
010101010111001010101
nice
Yup
!e
import code
c = code.compile_command("print(hi)")
i = code.InteractiveInterpreter(locals=dict(hi="hello world!"))
i.runcode(c)```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
hello world!
you may go with it, if you want

atleast somewhat better than exec
a programming language made with python very pog
A python language made with python is gonna be comedically slow
Whats c?
c programming language
python isn't made of C
python is just a concept
it's an idea
they said its made in c
So whats C made out of?
assembly afaik
C is a programming lanuage
Quick like faster then you can run
languages aren't made of anything
Whats that made out of?
Like fast fast
languages are just concepts, rules we set
@slate swan
C is defined as this and that
Why did you use disnake
python is defined as this and that
๐ญ
an assembler converts assembly to machine code afaik
Impossible, how are they made then?
it's up to people to write something else that can IMPLEMENT these concepts
๐ค
it's just like english
Alr
english is also a language
it's made of purely concepts and rules, it's not made of anything, it's not something you can see hold or touch
it's purely a concept, a set of rules
How do I create my own language? ๐ค
seriously
but it's going off topic
well not mine ๐ฆ
Thats weird
idk why but im trying to do it again
Oh hi there seb! Long time no see
๐
i tried use \u200 and bot crashed ๐
hi. Just hanging around in python-general more
this channel sometimes drives me insane
Haha u will want to keep away from this channel if u don't wanna lose your sanity ngl
try this maybe
place = '' name = '' level = '' for x in character_list: place += x[0] + '\n' name += x[1] + '\n' level += x[2] + '\n' embed.add_field(name='Platz', value=place, inline=True) embed.add_field(name='Name', value=name, inline=True) embed.add_field(name='Level', value=level, inline=True) return await client.say(embed=embed)
kinda complicated lol
done
yeah but i can virtualisate it on my mind :v
trying use \n\u200
oh
client.say is a thing?
Yes with some definitions
and crashed again :3
I was thinking of that
It's old yeah
Novia, done with the docs for Lefi?
No am not doing shit atm, exams ๐ฉ
Lmao
I hope u don't mean that literally
๐ณ
Nvm that was lame
;-; yea
I'm thinking of adding a log feature (better than old), what things I should log in server?
So basicially every single action I can think of?
Every single event you can use.
I mean I won't log presence update
that will be a lot of stuff to send to channels in embeds
Webhooks.
huh?
Use webhooks
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.webhooks "discord.Guild.webhooks") and [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"). The ones received by the library will automatically be bound using the libraryโs internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.7)"):
Will prevent the bot from getting ratelimited if many guilds get so many updates at the same time.
I have tried once but my brains can't handle this stuff
Time to make it handle hehe
Ah. Gotta make a discordpy webhooks repository, then.
does it build a embed by default?
Anyhow, you've got this example.
from discord import Webhook
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')
No
webhook.send is just as ctx.send.
sigh time to make a embed creator function
ctx.send.
embed creator?
async def create_embed(title, description, field, value):
embed = discord.Embed(title=title, description=description)
embed.add_field(name=field, value=value)
```smth like this?
class foo(discord.Embed)
``` do you mean this?
yes
now it has all the attributes and methods of Embed, you can even use that to create your embeds
you wont see any difference
how would that work? I can just import discord and use the embed from there as well and it would work the same way, right?
to create an embed now you just gotta do embed = foo()
then embed.add_field() or whatever you want
build embeds for webhooks without needing to do it again every time
add your own method to use the attributes you can do self.title and to call methods self.add_field()
basic OOP
I suck at oop
its useful for your life, you should learn it
I have been doing it a bit, but not this much
so just smth like this? ```py
import discord
class factory(discord.Embed):
def init(self):
self.embed = factory()
async def mod_log(self, title, description, field, value):
embed = self.embed(title=title, description=description)
embed.add_field(name=field, value=value)
return embed
follow pep8 and initialize the parent class with super()
you have to pass *args, **kwargs to it
to.. what?
to the constructor of the parent class
into the self.embed?
you need to define them as parameters of your constructor as well
I'm confused I don't understand what you mean

