#discord-bots
1 messages · Page 817 of 1
!d discord.BanEntry
class discord.BanEntry```
A namedtuple which represents a ban returned from [`bans()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.bans "discord.Guild.bans").
help me out😅
@pure tartan nvm found a better thing
just make everything lowercase and use if url is None:
^
Fetch a ban using guild.fetch_ban and get its reason
ok thanks
?
what fork are you guys using(if you are using one)
disnake
!d discord.Guild.fetch_ban
await fetch_ban(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry") for a user.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
wtf
Fetch ban entry in your listener and get its reason attribute
what version of python is this
do you know basic python?
10
3.10
oh and don't use '', told you
Thx
yeah I'm dumb, it's there
@terse stream don't enclose None in ""
!e "I" is "I"
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
its just None
that's the error.
oh
didn't know that error existed
same lol
It is not an error but a warning, I wouldn't call them the same
so i guess use == instead of is
It's just a warning tho
I've never made a mistake like that 😎
Or just use None datatype instead of "None"
yup
i like it like this ver
but m fetching url title and description as a string right........
None is not a string
its just emptyness
check line no 68
Off topic but is it possible to make a class which is a subclass of 2 other classes? For reference a class which is a subclass of asyncio.TimeoutError and a custom Exception based class too
yeah i don't see a problem
also this is off topic but you might wanna use a formatter like black
technically it should work right?
no offense but your code is very poorly formatted
mine?
yeah
caz i know the basics
!Pep8 guide gives you the neatest way to write code in py
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:
@terse stream
yup black is the best
same which api?
dont check the format just check the code whats wrong with it
mhhm?
pokemon?
the hell
https://pokeapi.co there are wrappers in python for this, but none of them are async
my client didnt got that msg until i pressed the reply lol
I'm in love
thats cool
.
comeon help me out ill but u nutella🥺
the fuck
do the same with every condition
I'm keeping it simple ```py
import pokeapi, asyncio
client= pokeapi.Client()
async def main():
pokemon: pokeapi.Pokemon = await client.get_pokemon(name/id)
asyncio.run(main())```
docs kinda raw but it looks good to me have you made a repo im down to help a bit
clean
i can try to help, i haven't really made an api wrapper myself yet and it would be a good learning experience if you don't mind?
yea will surely share the repo as soon as I'm done with some basics
Atleast the codebase
Everything's gonna be objects
I'd love it!
check line no 68 m fetching title description and url as string how can i use is None
send the link again
Great, you can dm me the repo link whenever you're able!
i gotta do objs in akeno but i dont want to since i need to make a request with all response headers so it has all attrs which doesnt sit quite well with me
are you gonna cache or nah?
there's no if statement there
That would be upto the user, there's a cache kwarg for Client which allows you to choose that
mhmm thats cool what do you use to cache?
a bool, by default set to True
Didnt find anything bout it
i used them in function wont that work?
local json since that's what the website returns
yeah a kwarg that takes bool value
just like this
if URL == 'None' and Title != 'None' and Description != 'None': no
if URL is None and Title is not None and Description is not None:yes
with a dict
i just use a dict
lolll
I use dict too,but in case the file restarts the json is read first
ok thanks
the data from api stasys same forever so recaching it won't make sense
i mean isnt it better tho? since the data gets removed for a fresh cache each session?
or am i confusing it with a backup or a log?
Or I may use that as an optional kwarg too
Nah you are at the correct point
I stated this for a Pokemon bot but now seems kinda fun
yeah make it a kwarg
imo api wrapper are fun
me who asks andy a question everyday
I'll make the cache kwarg accept a string, if the string is "memory" it will just cache in dictionary, if it's "disk" : memory + json
I'm probably gonna ask alot of questions too! Newbie in making API wrappers
which api?
huh? no I'm talking about while helping making this wrapper
unlike robin he makes apis and not api wrappers🏃
wrappers ain't too hard to make, especially if you know how an API works ( we r already in the discord bot channel ahem) a basic knowledge about objects , responses and dictionaries is all you need
ah lol
great! i have all of those haha
just a little bit of guidance should be good for me then
I'm always up for it
just http request and its methods what are websockets a gateway an api call response etc
thanks!
yesssir
i havent used websockets which seem hard imo but idk
since in a websocket you need to make a heartbeat to keep the connection alive
the pokeapi is a rest one so needs only gets
a gateway connection is not required
those are http request methods so it really doesnt matter
event
ey
not event()
You do event
we all are bad
No ()
if URL == 'None' and Title != 'None' and Description != 'None':
this is almost legitimate code
@bot.event
async def on_command_error(ctx,error):
if isinstance(error,commands.MissingRequiredArgument):
await ctx.send('Please provide all the arguments **Type NONE if you dont want to use something**!!')
```cause of this
just comparing strings and not NoneType
Type NONE if you dont want to use something
it's not a joke
it's made so that you can put a not-required argument that's after a not-required argument
how do i change the perms of a member in the guild? like give them admin or smth?
Give them a role?
no, just perms, or can that only happen with a channel?
Its channel and category based then
stop
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\testing\modules\config.py", line 92, in on_command_error
await self.error_channel.send(self.error_embed)
TypeError: can't send non-None value to a just-started coroutine
no
well the error says it all


for just ten....?
+5k secret xp
GG @slate swan , gr8 job on keeping the server alive 👍
(took that from MEE6)
that's bs
started on level 0
why not steal things from your own bot
why so many pings
@slate swan your famous
jeez
@slate swan do you want a fourth ping?
5pings
elementary. 36
but its other error ..
your pfp is sus
i swear if i keep getting pinged
does anyone know of a way to unban a user through the console?
!d discord.Member.unban
await unban(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
the bot console?
i mean you can use input but that isnt async
do you know of a way to unban someone like every 30 seconds or something
like a certain person
youre sus
what would you do once you get input?
why unban someone every 30 seconds?
well basically
add the member id ig
._.
no it's discord.Guild.unban(user, reason=None)
i made a server for someone and then they turned, but they are refusing to kick my bot, so i want to get rid of my bot. but then they banned me
Yes sus.
add it to where? How are you going to send the api request through terminal without interacting with discord app?
you can clearly say it says aliases
oh didn't read that
so i wanna unban myself using my bot.
cant you just add the id there?
what perms does your bot have?
admin
isn't that cheating?
it's their server
its my bot.. lmfao
just remove your bot then
unban yourself with your own bot thats kinda abusing power dont you think?
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
whoops
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<Config.get_channel() done, defined at c:\Users\PC\Desktop\testing\modules\config.py:24> exception=AttributeError("'_MissingSentinel' object has no attribute 'request'")>
Traceback (most recent call last):
File "c:\Users\PC\Desktop\testing\modules\config.py", line 25, in get_channel
self.error_channel = await self._bot.fetch_channel(ERROR_CHANNEL)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 1575, in fetch_channel
data = await self.http.get_channel(channel_id)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\http.py", line 275, in request
async with self.__session.request(method, url, **kwargs) as response:
AttributeError: '_MissingSentinel' object has no attribute 'request'
Ready
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\testing\modules\config.py", line 94, in on_command_error
await self.error_channel.send(embed=self.error_embed)
AttributeError: 'Config' object has no attribute 'error_channel'
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
hows it breaching TOS though?
Your using your bot to gain access to a server which the owner didn't want you in, just remove your bot from there
youre avoiding a ban which was set to you which youre trying to go over with your bot its probably not against tos but it seems wrong tbh you were ban for a reason no?
then why are you trying to unban yourself every 30 seconds?
seems like they dont want you in there server if you get banned everytime?
i literally made the server for the guy, passed ownership, and found out he's weird so i asked him to remove my bot when i left and he didnt
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
here make your bot leave
Giving yourself perms to a server?
make your bot non-public
im not giving myself perms
How does that not break tos
then he can't add it
dude its already in there
add the guild id and your bot will leave the server
okay
if you cant find the id loop through all the ids that the bot can see
bruh how i get the guild id if i cant join the server
!d discord.ext.commands.Bot.guilds
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
oh
check the name and id lol
Just look for yourself?
no sorry
bruh
sounds like a you problem
i cant get it because it says user is banned?
Seems like you're actually just trying to get revenge
^
not revenge i literally just want my bot out of the server
Look through your list
just make your bot unpublic
Find the id
then remove it from the server
bot.guilds
your question has been answered why continue?
!d discord.ext.commands.Bot.guilds
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
its a list?
it's a list of guilds
you're weird
just iterate through it
we answered your question 3 times
thanks
okay thats cool but where would i put the code?
we can't spoon feed it
most people dont say im weird but alr
this gives me bad vibes, not directly help you
same
If you have an eval command, use it. If not you can always create a dummy command
gtg later guys
wdym a dummy command, like what would i make it?
cya ig
a command you can run in another server
true
Literally just make a command
And have the code to leave inside of it
You're giving me very bad vibes. This is such easy code
no its not, what would i put after async, like what type of command, an on_join, like what?
WHAT TYPE
Prefix command
okay
and how would i send the command if im banned
in. another. server
okay
In a server you're not banned in?
your bot left the server?
yes
alr
thank you guys, i just didnt want him using my work
Okay?
better turn public bot off in your application settings
true
@bot.listen
async def on_message(message):
channel_suggestion_id = 941430665256251432
channel = bot.get_channel(channel_suggestion_id)
if message in channel:
embed = discord.Embed(colour=discord.Colour.red())
embed.set_author(name=f"Suggestion by {message.author}", icon_url=f'{message.author.avatar_url}')
embed.set_thumbnail(url='{}'.format(member.avatar_url))
embed.add_field(name=f"{message.content}", value='\n\u200b', inline=False)
await message.channel.send(embed=embed)```
Wait nvm
😭 i didnt see "await"
Wuts the error?
why it isn't working?
Idk tbh i've tried @bot.listen but it didnt work wit me. So you gotta change it to event and add await bot.process_commands(message)
File "C:\Users\30694\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\30694\Desktop\All\Gif Server Bot\main.py", line 315, in on_message
if message in channel:
TypeError: argument of type 'TextChannel' is not iterable```
try if message.channel.id == channel.id:
Instead of if message in channel
Hey guys, im developing a cog that is supposed to send a number to a user in DM's, and the user is supposed to repeat this number. Im using Discord.py.
anyone know how to get response from a user?
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
you just check if the user is the user and the channel isinstance discord.DMChannel
!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
interesting.
Thank you
can anyone help me rq
i just wanna confirm something
# Channels
welcome_channel = client.get_channel(839070995745603585)
will this work ?
so i can always do like
@client.command()
async def idk(ctx):
await welcome.channel.send("test")
wait
ill just try it myself im so smart why am i asking
do you mean await welcome_channel.send(…)?
yea sry lol
jolly good question
...
guys, how do i get my vs code file to debug as it keeps sending this message.
wrong file location maybe
.....
try:
...
except <exception name>:
...
bare exceptions are bad, so I won't recommend it
well done
yessir
Is there a way to check if a user's dms are off without using a try & except method. I'd like to be able to check without having to send a test message to the user.
error handlers?
shit I just realized what I said
well...
try except is the only thing I can think of
Don't think so
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.

Unfortunately no
@client.command()
async def serverinfo(ctx):
"""Displaying server info"""
embed=discord.Embed(title="Server Information")
embed.add_field(name="Server Name", value=ctx.message.guild.name, inline=True)
embed.add_field(name="roles:", value=(ctx.message.guild.roles), inline=True)
embed.add_field(name="Members:", value=len(ctx.message.guild.members))
embed.add_field(name="Channels:", value=len(ctx.message.guild.channels))
embed.add_field(name="Members:", value=str(ctx.message.author.mention))
embed.set_footer(text="Check out discord. gg/shops for cheap and affordable Discord bots and other services")
await ctx.send(embed=embed)```
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.1.value: Must be 1024 or fewer in length.
What's wrong here
Already mentioned in error
Reduce the text
Well, from where specifically
embed.add_field(name="roles:", value=(ctx.message.guild.roles), inline=True)
^^^
ah
guild.roles are exceeding 1024 char length
How do I state the number of roles?

len
Umm I think len(...roles) ?
okay thanks
wait
Also see this value embed.fields.{this_value}. to know which field is exceeding the limits (starts programatically, ie 0 for first field)
oooh
If a user sends my bot a message, how can i read this message?
is there some sort of on event?
or how does that work
You mean dm messages?
yes
Bot receives it with same event MESSAGE just like other messages
really
check if message.guild is None in on_message
1 sec
@commands.Cog.listener()
async def on_message(self, *, ctx, message):
if message.guild == "None":
#do stuff```
like this?
my bot is sending the message a lot of times... can any1 help me?
@client.event
async def on_message(message):
if 'Nota'.lower() and 'Razão'.lower() and 'Staff'.lower() and 'Nick'.lower() and ':' not in message.content and message.channel.id == 941458805676462090:
await message.author.send('**EI**! O canal [#941458805676462090](/guild/267624335836053506/channel/941458805676462090/) não foi feito para bagunça! Utilize ele da maneira **CORRETA**, por gentileza.')
await message.delete()
else:
mensagem = message.content
channel = client.get_channel(941458805676462090)
await channel.send('**NOVA AVALIAÇÃO RECEBIDA**\nEsta avaliação foi feita pelo {0}:\n\n{1}'.format(message.author.mention,mensagem))
pass
if message.guild == NoneType:
Do you know how to check if some object is None?
@commands.max_concurrency(1, per=commands.BucketType.default)
No xD
'Nota'.lower() and 'Razão'.lower() and 'Staff'.lower() and 'Nick'.lower() and ':' not in message.content this is almost certainly not doing what you think @dusk dust
Just compare it to None using is
yes, this is working perfectly, but the bot is sending the messege a lot of times
thank you
np
i am going to test
Actually it's listening to it's own messages too, which creates it send messages recursively
I can assure you that it's not working as expected, do you expect the message to not be sent if something like "nota" is within the message content?
Add a check to see if messages sender is not the bot
Or "staff" etc
you can make it so it does nothing when reading its own message, or use the command i sent above.
Because it's not checking that
At the very least, you have a lot of redundant things in that if-statement that do effectively nothing
@slate swan if message.guild is "None": this right?
if 'Nota'.lower() and 'Razão'.lower() and 'Staff'.lower() and 'Nick'.lower() and ':' not in message.content and message.channel.id == 941458805676462090: is functionally the same as if ':' not in message.content and message.channel.id == 941458805676462090:
None is a string and not the NoneType
Sorry not trying to sound rude but you should take it to #python-discussion instead of discord bots 🛐
its fine here?
no
omg
is None
whats i did
- when i type something different of:
"Nick: jsadasd
Staff: asjdjsd
Nota: asdasd
Razão: asdsad"
no?
if message.guild is None:
tysm
what's wrong here?
@commands.command(aliases=['photo', 'img', 'icon', 'av'])
async def avatar(self, member: discord.Member = 'none'):
if member != 'none':
aembed = discord.Embed(title=f"{member.display_name}'s avatar")
aembed.set_image(url=member.avatar_url)
aembed.timestamp = datetime.datetime.utcnow()
await self.send(embed=aembed)
else:
aembed = discord.Embed(title='Your avatar')
aembed.set_image(url=self.author.avatar_url)
aembed.timestamp = datetime.datetime.utcnow()
await self.send(embed=aembed)```
@dusk dust
At the very least, there's a lot of redundant stuff here
omg
why is everyone making None a string today?????
but i want to check if the person was typed
"Nick: rtahd
Staff: dahsdj" ...
Well that's not what's happening here, it sounds like you want to check if "Nick" is in the message content, or if "Staff" was in the message content etc
Have python like released some changes to None or what, I've been out for so long
None is a Nonetype and not a string
That's what we call not learning python
the error is 'Context' has no attribute 'avatar_url'
but this is just the opposite
why would python make NoneType a special str
no?
because context doesnt have that attr member does
Yes because 1st param passed is context not member
Oh my bad, you're checking if they're not in the message content correct?
so how can i fix that?
Right, well that's not currently what's happening. If you wanted to do that you would need to do if "Nick" not in message.content and "Staff" not in message.content and ..., doing if "Nick" and "Staff" and ... not in message.content is not correct, it makes sense in English but it's not doing what you think it's doing in Python
make a member argument and make member context because right now member is context
I'm also not too sure what the .lower() is there for
oof...how?😁
It's sort of pointless if you're just calling it on a string literal
Just change the literal instead
now i have member: discord.Member
why does this show as a error?
i am not understanding, sorry. but the if's are working, i just want to know why the bot sends several messages a lot of times
delete the tab in the decorator
@bot.command and async def must be the one under the other
and your indents arent correct
Tell me what happens when you send a message containing "Nick" or "Staff" and don't have a :
Your "member" parameter is assigned to .Context and your .Member doesn't exists. Your function receives a value like (context, member, ...) but you took it like (member, ...) hence declaring .Context to your "member". To fix, just accept a ctx before member
it should be 4 spaces or a tab for each level of indentation
The if-statement will be True
it is in cog
self is the argument thats given to access a class it doesnt matter it will always be first
oh ok
ahhhhhhhhhhh
self, ctx, member: discord.Member = None
is how your params should look like
Anyway, as to why it's sending multiple messages
It's just responding to it's own messages
So you'd probably want to just throw a ```py
if message.author == client.user:
return
Up the top of your on_message so that it ignores itself
okay
'InfoCommands' object has no attribute 'authot' -_-
its author
not authot
f
you should read your errors
sorry
it will help you
wait, i wrote it wrong here. It is author
you did self.author
its ctx.author your class has no attr with author
ah yes
ctx does have a author attr do
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
lol
i finally found it! thanks so much and sorry if i was annoying
nah no worries you werent
: )
❤️
btw check how satisfying is my pfp
very clean
yeah i love this bonfire
lol
how to i restart my discord bot? like turn off and back on?
what for?
vscode
yea
you can use cogs and reload it so the bot stays on and gets new commands
!d discord.ext.commands.Bot.reload_extension
reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
whats that?
the reload your cogs
ok do i paste it in ?
first do you have cogs?
nah
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
man, discord fucked up again
hi! it's me again
i have this:
@bot.command()
async def server(ctx):
embed = discord.Embed(title = f"{ctx.guild.name} Info", description = "Information of this Server", color = discord.Colour.blue())
embed.add_field(name = '🆔Server ID', value = f"{ctx.guild.id}", inline = True)
embed.add_field(name = '📆Created On', value = ctx.guild.created_at.strftime("%b %d %Y"), inline = True)
embed.add_field(name = '👑Owner', value = f"{ctx.guild.owner}", inline = True)
embed.add_field(name = '👥Members', value = f'{ctx.guild.member_count} Members', inline = True)
embed.add_field(name = '💬Channels', value = f'{ctx.guild.text_channel_count} Text | {ctx.guild.voice_channel_count} Voice', inline = True)
embed.add_field(name = '🌎Region', value = f'{ctx.guild.region}', inline = True)
embed.set_thumbnail(url = ctx.guild.icon_url)
await ctx.send(embed=embed)```
and the error is `'Guild' object has no attribute 'text_channel_count'`
Have you read the error?
Why are you using random attributes and expecting they will work?
!d discord.Guild.text_channels
property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
!e
print(len("text"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
4
You use len() on a list to get how many elements it has
ok like this
len gets the length of how much elements something has
its an example*
ok
i wasn't supposed to paste this in the code
no
it was an example to show you how len works
ok
len({ctx.guild.text_channel_count}) like this?
go for it
I just told you text_channel_count doesnt exist?
I showed you above what to do. Do you not understand something?
discord.interactions isnt a module
do u know replit?
Traceback (most recent call last):
File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.devcog' raised an error: ModuleNotFoundError: No module named 'discord.interactions
thats the error we are getting
im getting so much pings
sorry
then what do we do to fix it?
im confused on this
confused on what
Traceback (most recent call last):
File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/scream/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.devcog' raised an error: ModuleNotFoundError: No module named 'discord.interactions
this is what is poping up
oh my god
Then don't import it...?
then what is the error?
really why use this lib
its getting called
idk its your code im not a fortune teller?
you want me to grab the solution from your mind?
im having a headache already tbh
im actuall0y confused about this tho it js dont make sense
it does
https://github.com/discord/discord-api-docs/issues/4483
idk if you already read this or you did on the disnake server
ill read it later
!e
import nothing
@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 'nothing'
it's not even basic python is more of logic thinking 
imagine you want to import something it doesn't exist 
exactly
then what is the error
import discord
from discord.ext import commands
import keep_alive
import json
from asyncio import sleep
import colorama
only imports
its in a cog
ModuleNotFoundError: No module named 'discord.interactions
👁️👁️
ModuleNotFoundError
not importing it how
guys what does it mean i can't read 😢
👁️👁️
import discord
from discord import commands
only imports in cog
bro
ModuleNotFoundError
only raises when trying to import a module
python just wont break for no reason
if your getting errors its most likely an error with your code and not internals
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.devcog' raised an error: ModuleNotFoundError: No module named 'discord.interactions
👁️👁️
are you blind bro
if health2 <=0.0:```
would any of you happen to know why this'd return true if health2 is 40.0 cause it is for me
for a discord bot so figured it'd be more appropriate to ask here but ok
that snippet isnt really related to it your saying why an if statement returns True
python general is more appropriate imo
!e
print(40.0<=0.0)
@sick birch :white_check_mark: Your eval job has completed with return code 0.
False
don't know about that
hi robin hyd?
@commands.command()
async def uptime(self, ctx):
now = datetime.datetime.utcnow() # Timestamp of when uptime function is run
delta = now - start_time
hours, remainder = divmod(int(delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
if days:
time_format = "**{d}d {h}h {m}m and {s}s**"
else:
time_format = "**{h}h {m}m and {s}s**"
uptime_stamp = time_format.format(d=days, h=hours, m=minutes, s=seconds)
em = discord.Embed(description=f"{self.bot.user.name} has been running for: {uptime_stamp}")
await ctx.send(embed=em)
Whats wrong with my uptime command? I made it back in august , Quit discord came back last month, most of my cmds dont work anymore so im fixing them , but this one sends no error at all
is start time defined?
on replit is it possible to make a database specific to a user or server
you can just make a table for a user or a server
yeah thought that was a solution just making sure there isn't already like a separate thing for it
nah not really just make the tables in same db
replit's db is slow, just use sqlite or something
replit db? yikes
yeah its bad slow
!pip replit
they have it integrated for projects
i know what it is, just it's pretty bad
ouch
like mongo but horrible
you know i never got the appeal of replit or any of their "tools"
andy, how do i get the Client's latency in rin?
what the fuck
oh ok
i tried client.gateway.heartbeat but it returns a dict
or is it not available yet?
Gateway.heartbeat is the heartbeat payload
I haven't added the latency, I can do that rq by taking times from last ACK'd heartbeat
whats a ACK hb
Acknowledge
ah ic
ohh, and what about the events documentations ? :c
docs is the part that sucks while development
You should just read the source code for now, https://github.com/an-dyy/Rin/blob/master/rin/gateway/event.py
bro.
Only the frontend methods are documented in this file though
Any particular question then?
😭
Cause I can probably answer
ah, line 352-422 has all the events listed
It was a pain writing them out
I made the events that way to make it easy to overload wait
Does your wrapper have more events than dpy and it's forks?
Has the newer events that discord.py doesn't have due to it being archived, idk about the forks though they probably have 100% support
The wrapper doesn't even parse all the events yet, just allows for them to be dispatched at the very least
I still need to add those sadly 😔
I mean development seems to be progressing fast
but andys wrapper has collectors those are cool
not really progressing fast 😔
bro you have one job🧍♂️
rin/gateway/handler.py lines 124 to 130
if code == OPCode.HEARTBEAT_ACK:
if self.last_heartbeat is not None:
self.latency = (
datetime.now() - self.last_heartbeat
).total_seconds()
_log.debug("GATEWAY ACK'D HEARTBEAT.")```
Welp I did my one commit for the week, time to go back to being lazy
nice commit
The parser code for gateway is so disgusting
Someone help me refactor, perhaps in a more decentralised way
😔
Yeah bro I got you
I feel like I should do model specific parsers, splitting up parsers into the spots where certain models use them
But it would be harder to do stuff
why so?
The parsers are easier to use in the same file cause they can be interconnected
parses are for strings i suppose right?
Parsers are for the dispatch data received from the gateway
to parse the data?
It turns the raw dict, e.g message dict into a message object for you to use
yeah it parses the data
i hate myself for listening to watergazes
Perhaps I will do a parser refactor before I do commands

Bro
Cause this is something I've been wanting for a while
You agreed
im joking😭
Perhaps something procedural in design
💀

Best way to automatically parse the events to their own classes, like on message in message class would be to do something like
event_type = "Message"
parsed = eval(f"{event_type}({json})")
Provided Message is a class name 🤣
chill with the funny words
bro
https://github.com/an-dyy/Rin/blob/c07aa237f6e9b982f6ce607f44125dbcc23920cc/rin/gateway/handler.py#L139-L145 I basically already do that
rin/gateway/handler.py lines 139 to 145
parser = getattr(self.parser, f"parse_{event.name.lower()}", None)
self.client.dispatch(Events.WILDCARD, event, data["d"])
if parser is not None:
return self.loop.create_task(parser(data["d"]))
return self.loop.create_task(self.parser.no_parse(event, data["d"]))```
But in a safer way, without eval
Damn. So u ain't using multiple if statements to check the event type lmao
i just parse the data for each endpoint🏃
that would be pretty idiotic
Yea there are many
jeez
Oki
thats allot of events
Hunter contribute and help me decentralise or make the parsers procedural
You've made a wrapper before so it should be light work
Uhhh, I myself haven't coded since a month or two now idk
your smart words always give me strokes
Whose
Actually there is no way for me to make this procedural
What do u even wanna do
I will have to manually add each one, or at the very least make a good system for adding them
I want a sort of generic builder
But for parsers, but that's not trivial
Generic builder?
Docs explain it perfectly tho
not rlly
Like imagine how my event class currently works. It works with any future event and all the current events with only the event name
I don't need to make any more classes, functions, etc
andys
How i use Custom Status?
for bots you cant
Yes for bots
nope you cant
oh
Hmm, too complex ig
bots dont have access to custom statuses
Ohk
Can you give an example?
😔 I don't wanna spend weeks adding all the parsers with that kind of scalability
👁️👁️
Uhhhhhh, Nova is there
I don't think I'll let nova do a core PR 😔
😂
😭
Blanket?
Blanket is working on his web framework
is it just me or everyone is working on something except me
Sad
lol
Aren't we all here because we work on something? 
No. I'm here became I'm bored
bro
OOHHH
?
I can make the parsers generic, ig then pass Event("Blah") to it perhaps
Hm?
Yea
And then it would register that parser to automatically listen for the event
i mean ig you can it would be cool
But this would mean I need to make them classes
A generic method wouldn't really work well
Wait wait wait... My idea of a simple parser would be...
json = await response.json()
event_type = json["event"]
parsed = eval(f"{event_type.capitalize()}({json})")
await bot.dispatch(...)
i mean that doesnt look bad ig
whats ({json}) for lol
I need to do a lot of things inside of the parser manually
So at the very least I want to make it easier to scale
To pass the json to the class
ah lol

Like?
Ah, the extra processing to look in the cache too?
the heck is this deco for
@attr.s(slots=True)
and what does this operator do :=
what does this operator do :=
assigning in cool way (if statements)
bro
Decorator is to make a dataclass with slots
🏃
Walrus
if role := discord.utils.get(...) == None:
print(role)
else:
print(role)
Vague example, done cry about it
basically just
if (a := 2) > 1:
print(a)
``` prints `2`
how do i set this up
ah so a is a var and your making the var and comparing it?
yes
cool thx
the tutorial says it?
What's :=
Can someone tell how to check if a message has an attachment?
!d discord.Message.attachments
A list of attachments given to a message.
if message.attachments:
print("Message has an attachment!")
if not message.attachments:```
I need a better example
Doesn't work
Sure
bro it just makes a variable and compares it
@final iron
It doesn't work.......
It assigns and compares the variable in one place
Oh
Same as first defining a role and then comparing it
why havent i been told this before
Idk
🏃
.
What's message?
Same
Most probably the message doesn't has any attachment
lmaooo
Uh just a message
Yes it doesn't!
But it doesn't do whatever in if not message.attachments:
no ive never dealt with attachments🏃
message.attachment returns a list of attachments (which includes all types of files) in the Message
not message.attachments would be True if the message has no attachments
^^
Yeah...... my code was correct I didn't add a return due to which it didn't return when the attachment wasn't passed
@bot.command()
async def recognize(ctx, url = None):
if url is None:
if ctx.message.attachments:
attachment = ctx.message.attachments[0]
url = attachment.url
else:
em = discord.Embed(title = "No attachement or URL!", description="Hey man you gotta send a file or a URL to recognize the music from -_-", color = bot_embed_color)
await ctx.send(embed=em)
return
query_url = f"https://some-cool-api.herokuapp.com/recognize_music?url={url}"
async with aiohttp.ClientSession() as session:
async with session.get(query_url) as resp:
res = await resp.json(content_type=None)
title = res['track']['title']
background = res['track']['images']['background']
coverart = res['track']['images']['coverart']
url = res['track']['share']['href']
subtitle = res['track']['subtitle']
em = disnake.Embed(title = title, url=url, description=f"by **{subtitle}**", color = bot_embed_color)
em.set_image(url=coverart)
await ctx.reply(embed=em)```
if a := 1 > 0:
print(a)``` is equivalent to ```py
if a := (1 > 0):
print(a)``` iirc
so, its a:= True
ohhh yeah a is the expression which is True
right thanks
async def callback(self, interaction: discord.Interaction):
global item
id = interaction.user.id
coin = database.check_coin(id)
s = int(price[item])*int(self.values[0])
if coin >= s:
await interaction.response.send_message(
f'{interaction.user.mention}, You bought {self.values[0]} {item}! thanks for shopping with us!')
database.add_item(id, self.values[0], item)
database.decrease_coin(interaction.user.id, s)
if self.values[0] == 5:
if item == "seed":
if random.randint(2, 2) == 2:
database.add_item(id, 1, "super seed")
await interaction.response.send_message(f"wow, {interaction.user.mention} is getting a :superseed: super seed!")
else:
await interaction.response.send_message("not enof money E")
i want that code work like this:
i buy 5 seeds
pick random
if it's 2, it will gimme super seed and send message
how
if random.randint(2, 2) == 2 will always be True
global's, yikers
and what's self there? a view class?
Why not just make an attribute?
yes, ik, that's just for test, but even when it's true ut's not send any message or gimme super seed
:wut:
yes
What
what attribute
!e
class TestClass:
def __init__(self):
self.attribute = None
def method(self):
self.attribute = "hi"
print(self.attribute)
TestClass().method()
@final iron :white_check_mark: Your eval job has completed with return code 0.
hi
Probably terrible example
you could have just TestClass().attribute to get the value :p
but that would return None
yeah since thats the original value
ok, i not understand, but here's my code
class amount_(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='1', description='1 item',
emoji=':1_:'),
discord.SelectOption(label='2', description='2 items',
emoji=':2_:'),
discord.SelectOption(label='3', description='3 items',
emoji=':3_:'),
discord.SelectOption(label='4', description='4 items',
emoji=':4_:'),
discord.SelectOption(label='5', description='5 items',
emoji=':5_:')
]
super().__init__(placeholder='how much', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
global item
id = interaction.user.id
coin = database.check_coin(id)
s = int(price[item])*int(self.values[0])
if coin >= s:
await interaction.response.send_message(
f'{interaction.user.mention}, You bought {self.values[0]} {item}! thanks for shopping with us!')
database.add_item(id, self.values[0], item)
database.decrease_coin(interaction.user.id, s)
if self.values[0] == 5:
if item == "seed":
if random.randint(2, 2) == 2:
database.add_item(id, 1, "super seed")
await interaction.response.send_message(f"wow, {interaction.user.mention} is getting a :superseed: super seed!")
else:
await interaction.response.send_message("not enof money E")
and in the method it gets re assigned
hi okimi
hi
view class code:
class amount(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(amount_())
i asked what's self there, and its a Select
^^^
classes should be in PascalCase
oh
what if not
you wont follow pep8
anyways, where does the variable item come from, and i dont see you using it anywhere other than database.add_item(id, self.values[0], item)
It doesn't follow pep8. Some employers just throw out resumes that don't follow pep8
functions should be snake_casing and variables, classes should be PascalCase and camelCase is for nothing lol
class shop(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='brew stand', description='A brewer tool', emoji=':brew:'),
discord.SelectOption(label='bottle', description='to store water', emoji=':woterbottle:'),
discord.SelectOption(label='seed', description='farming is really need this!', emoji=':seed:'),
discord.SelectOption(label='crafting table', description='u need this to do some things', emoji=':crafttable:')
]
super().__init__(placeholder='Shop items', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
h = discord.Embed(title="how much?", description="", color=interaction.user.color)
view = amount()
if self.values[0] == "seed":
global item
await interaction.response.send_message(embed=h, view=view)
item = self.values[0]
else:
id = interaction.user.id
coin = database.check_coin(id)
s = int(price[self.values[0]])
if coin >= s:
await interaction.response.send_message(f'{interaction.user.mention}, You bought a {self.values[0]}! thanks for shopping with us!')
database.add_item(id, 1, self.values[0])
database.decrease_coin(interaction.user.id, s)
else:
await interaction.response.send_message("not enof money E")
!d discord.ui.Select.values
property values: List[str]```
A list of values that have been selected by the user.
will it hav error or just some friggin styling
hm
Again, it should be in PascalCase
It's bad practice.
so no error?
!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:
pycharm will scream at you
It's writing bad code
:v ok
and it makes it more readable to everyone hence pep8s existence
more readable code-> easier for other ppl to understand
general style all python devs should follow
:vvv ok
ok, from discord.py server, they said that i need to interaction.followup.send
i try but dont work
does it not respond at all?
guess you wont get nothing for christmas
wait for 25 dec this year
#esoteric-python gives me strokes
you got a nice strap there-
So many PEP8 rules being broken
lolll
mf esoteric python is like boiling the egg without the egg 💀
help
nah its like boiling a fried egg
boiling the egg, but all the "g" is silent and the "e" is called pep8
esoteric python isn't just about unstylish code
its about breaking python lol
#esoteric-python is like brainfuck but more understandable
help #2
@slate swan current Cache implementation
https://paste.pythondiscord.com/exisavixow.py
its accessed with Client.cache ,any thoughts?
should i combine the class in Client itself ?
nah
iterate thru Guild.roles and use Role.permissions to check if the role has the permission you need
maybe make the method
get_sprite
idk i like it better imo
and why is client in the init?
in akeno i just accessed the methods of the cache class
My cache now
bro
yoink
your implementation is bad
how bro
how is this bad
https://github.com/Okimii/Akeno/blob/main/akeno/cache.py
gotta remove the preview embed🏃
Anyone know what I did wrong?
message.content
ohhh
attrs
i need to acess some attributes of Client inside the cacheimpl , remember we talked about the option of caching in memory and disk right? Client.cache_type is required in the CacheImpl to acess its value
!d discord.Guild.roles
property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
!d discord.Role.permissions
property permissions: discord.permissions.Permissions```
Returns the role’s permissions.
ah ic i just had multiple inheritance
sprite_cache isn't ideal, you should be caching sprites when also caching the pokemon. Not caching all at once during the getattr
fixed it but still doesn’t work when i run it on discord
It would be be a lot faster than what you got rn for that
As it is O(n) where the other would just be O(1)
oh no time comps
im avoiding it since get_pokemon is a method in both classes
the first coro should be in the bottom
coro?
ah ic im not lol
coroutine
what’s that? sorry i’m new 😭
await bot.process_commands(message)
ohh ty
oh yea, its accesiable with get_pokemon()['sprites'] too, i just wanted to make a shortcut for that
i did this
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
takes an argument
and imma test it rn
not right
one is in the params of the event and the other is the one in the process commands coro
But then why re-cache when accessing sprite_cache_
btw why make this a property?
@property
def pokemon_cache(self) -> dict:
return self.pokemon_cache_impl
it returns the complete dict... and you dont need to call it for that
because it returns a dict and doesnt take arguments?
CacheImpl.pokemon_cache is all you do
yeah ik
yea thats dumb, imma fix all those things
i should do that for akeno lolll

idk if its good or not, but im trying to make most of the things as properties
i mean if it doesnt need to be called with arguments i think its fine
almost all functions which return a dict are properties there
yeah
https://github.com/an-dyy/Rin/blob/master/rin/models/cacheable.py Heres how I do my caching
god level cache incoming
I do all that extra stuff to make the dict also act as as a sorta collections.deque without being a list
fr
Thus allowing for a popleft at O(1) getitem instead of O(n) for list iteration
You can just think of, O(1) being constant time, no matter how many items it will always be the same time
Then you can think of O(n) as linear time, the time goes up with the amount of items you are dealing with
ahhhh so O(1) is constant time which never changes and O(n) is linear time which changes by amount?
and how would you know about it being constant or linear?
Well iterating through a list is O(n) right?
yes
The more elements in the list, the longer it takes?
yeah because you dont know how many items it has so the time changes
ahhhhhhhh

