#discord-bots
1 messages ยท Page 744 of 1
no elifs?
Also it shouldn't really return something
my command has:
@commands.command()
@commands.bot_has_permissions(administrator=True)
And yeah add elifs
Can you show us create_embed method?
async def create_embed(self,ctx,description,author):
print("Error embed")
em = discord.Embed(description=description,
color=0xeeffee, timestamp=ctx.message.created_at)
em.set_author(name=author,icon_url=self.bot.user.avatar_url)
em.set_thumbnail(url=self.bot.user.avatar_url)
await ctx.send(embed=em)
Okay error is not in there
what IDE are you using?
PyCharm
ah I did have an error handler, I removed it now and got this error. why does it say * is not supported?
bet is none
bet is None
Try to do debug it using breakpoints
okay, gimme a minute
@humble granite I still have the feeling that there's a local error handler
debug the on_command_error event and your create_embed async func
Does pycharm debug async apps alright? Cause VSC can't, it only raises unhandled errors
oh okay, that makes sense. so I need to put each embed inside if function they are being used
Just debugged it and it tells me the create_embed async was called 2 times
well it actually does but if you take too much time it will raise a timeout error i think
Nice
something else is calling the create_embed, is as Exenifix said, maybe you have a local error handler in your bot object
how can i add roles to a channel with specific permissions what method? i looked at permissions_for but its just returns and i cant find a channel update
didn't get any error. just the print from the code down below
async def create_embed(self,ctx,description,author):
print("Error embed")
em = discord.Embed(description=description,
color=0xeeffee, timestamp=ctx.message.created_at)
em.set_author(name=author,icon_url=self.bot.user.avatar_url)
em.set_thumbnail(url=self.bot.user.avatar_url)
await ctx.send(embed=em)
@humble granite search for regex @.*\.error in code
No, I'm talking about your on_command_error
since thats where create_embed is being called
you also have self.bot.user.avatar_url in both author and thumbnail
do you know if does a function has something which can tell you where it is called?
You mean set perms for channel?
for a role yes
@commands.Cog.listener()
async def on_command_error(self,ctx, error):
if isinstance(error, commands.CommandNotFound):
return await self.create_embed(ctx,f"d","Missing Permissions")
elif isinstance(error, commands.MissingPermissions):
return await self.create_embed(ctx,f"Y","Missing Permissions")
elif isinstance(error,commands.BotMissingPermissions):
return await self.create_embed(ctx,f"Missing perms","Missing Permissions")
else:
print(error)
return await self.create_embed(ctx,f"u","Unkown Error")
I am just doing a different method
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
why return?
just print or send
Search that regex like you might find the error handler @humble granite
Okay @vale wing
hmmm. gives no error. but theres a new problem now.
It sends the message 4 TIMES and i get it 2 times in the log
cheers
just removed return and i get the message still 2 times
@humble granite so you didn't find any code matching that regex?
yes
another thing, what error does it actually send?
Hello
@client.command(aliases=['user','info'])
@commands.has_permissions(kick_members = True)
async def whois(ctx, member : discord.Member):
embed = discord.Embed(title = member.name , description = member.mention , colour = discor.colour.#00FFFF())
embed.add_field(name = "ID", value = str(member.id), inline=True )
await ctx.send(embed=embed)
Is giving syntax error in last line
Other commands send single response?
Or just use elif
like MissingPermissions or what
they are using elif
what's the error?
indents?
I told (you?) what to replace that thing with
It's showing invalid syntax in last line
You have a space before adding your comma.
It's not working
what invalid syntax? It usually gives extra text
discoc.colour.#00FFFF() is invalid color construction
did you check your indents?
so I'm not getting any error from that. only the print from my create_embed async.
So if i add on_message event, it happens nothing.
If i call another command without the @commands.bot_has_permissions, it does not happen.
But it's showing invalid hexadecimal literal
Indents are correct ig
@client.command(aliases=['user','info'])
@commands.has_permissions(kick_members = True)
async def whois(ctx, member : discord.Member):
embed = discord.Embed(title = member.name , description = member.mention , colour=0x00FFFF)
embed.add_field(name = "ID", value = str(member.id), inline=True )
await ctx.send(embed=embed)```
I'll just write you the code 1 sec
But it's showing invalid hexadecimal literal
Just added a ctx.send into that on_command_error and it gets called one time
@client.command(aliases=['user','info'])
@commands.has_permissions(kick_members = True)
async def whois(ctx, member : discord.Member):
embed = discord.Embed(title=member.name, description=member.mention, color=0x00FFFF)
embed.add_field(name="ID", value=str(member.id), inline=True)
await ctx.send(embed=embed)
Is how it should be.
shouldn't the color be in string? or am i wrong?
alr
Do you still do return await self.send_embed?
yes
Without the "" it's showing incal hexadecimal
But with them it's not showing
Just write await self.send_embed
Ah sorry.
so, i was right
Yes ig
colour?
IT'S COLOR LOL
yo yo caps
It should be colour
color and colour, bruh
I swear both don't work.
im canadian so i use colour
Color is an alias to Colour
Color is not working
I literally remember trying.
confuse 100
๐ฅฒ

Did you use the code I sent?
I think even docs say it like that
I edited other stuff too.
Mk
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").
There is an alias for this called Color...
YO
a
lets go
In the source code it is py Color = Colour
I am copying it wait
@humble granite
canada ftw
Surprised tbh.
just did that. it still happens
"There's an alias for this called Color..." 
no no no no no
Bruh, that's why. xd
so i've just made a ctx.send instead of the self.send_embed. it sends the message only 1 time
I thought you would of.
@humble granite is your bot like very big
Man this will get me crazy
Cause if it's not I'd like to look at that thing by myself
It's not working
what is the definition of "big"
like, 2000 lines?
What's the error?
> 500 lines
error?
nah, not really. its jsut a test with the main file 500, and 2 cog files with 100 lines
Is your indentation correct?
Yes
send full error
What are you using to run code?
Ok
Wait what do you have in the main file?
Replit
Ok could you pastebin the file with your main command (exclude the token if it's there) and send it
Replit?
i'm gonna pastebin the cogs with the error messages
Now
brb
I need the cog with command more
that too
It doesn't seem like the problem is in global handler
What should I do now should I do it in vs code ?
Do you have other error handlers? Inside your main or your other cog?
There's another thing I can't really tell until look at the whole thing
no
Already asked him, he said no
Me ?
No
Ok ๐ฅฒ
I remember there's a quick way to change indentation

Can you send a picture of your code if it's small enough to fit.
@stable berry arrow very gud ik
Depends on IDE
In pycharm if you evidence a block of code and press tab it will indent the whole block
He said his IDE is VSC iirc
๐
can i send links in here?
Yes
Yes
depends the link
Pastebin
https://pastebin.com/R49wX80F <--- thats the error handler cog file. (error.py)
lemme paste the one for the command
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Does the python bot have malicious links filter btw
Seems fine except it shouldn't return anything
@limpid thicket
I didn't paste that though.
!e py print(type(0x123))
@manic wing :white_check_mark: Your eval job has completed with return code 0.
<class 'int'>

There isn't meant to brackets nor in a str
It's not working without those
Ok
@client.command(aliases=['user','info'])
@commands.has_permissions(kick_members = True)
async def whois(ctx, member : discord.Member):
embed = discord.Embed(title=member.name, description=member.mention, color=0x00FFFF)
embed.add_field(name="ID", value=str(member.id), inline=True)
await ctx.send(embed=embed)
Just use this and then paste image of error.
Me pasting this
@vale wing https://pastebin.com/pem8f9qJ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.

Hm I should look at these more attentively
it doesnt seem to work as it is
@humble granite if you call any other command that sends something does it send that once or twice as well?
Thanks duck bot worked @limpid thicket ig i copied hrlo77 s code
only the one with the @commands.bot_has_permissions()
xD, was going to say.
Add another command with simple text response and test

When you test this you do it with both bot and user without permission?
Thanks ezenifix and duck ( thanks alot)
UPDATE: I said it sends the message 1 time if I replace the self.create_embed with ctx.send. Now it sends that 2 times too. with reset token.
the one where the bot needs perms
I still think that the problem is that you return your error handler
did it already without return. still does that
The last thing that remains is that you are trying without closing the current execution ๐
Better reboot your PC or restart pycharm, you might have launched a subprocess and haven't terminated it
takes some time for me, ill be back
just done that. still sends it 2 times. with reset token.
I've even created a on_message to print me if the bot is processing a command and it did trigger 1 time
no
Do you know how to do custom checks?
Only error handler?
depends on wich check
Just do one which checks the permissions of your bot
so I've just executed the command with a custom error and this gets called twice. it's even in the log
But no that is impossible, don't do that
The only thing that could make this happen is that you return, i know that you already tried without it but it is the only reason it does that. There is what happens: when you call the command the bot raise the bot_missing_permission error, then in your error handler you return the function which means that you return to the point where it checks bot permission, from that it goes to your command again, the bot attempts to ban the user but it doesn't have enough permission so the bot raises again bot_missing_permission error and it does again the same thing
Um
Return doesn't really return to the check
If the check is failed it just raises an error and stops on working with command
It returns to the point where the function is called
To know if i'm right we can do one simple thing:
@humble granite add a for loop before you execute the command, make it in range 5, it should print 6 times the error
Does anyone know how to code reaction roles?
Cus I've looked everywhere
nothing works
Use the on_(raw_)reaction_add event.
on_raw_reaction_add is better
Depends
Whell the bot can't store messages in the cache while it is offline
also all the code ive tried is channel dependent, meaning that it only works in 1 channel of 1 sever, how do I get around that?

that's a bit of a tongue-twister topic
you need to understand that commands are context based: they'll execute differently based on the conditions met
for example, ctx.guild is not an attribute that exists inside of a dm channel context
You have to store the messages objects that use the reactions in a variable (they will not work anyway after you shut off the bot, to make them permanent you should save the message id to a database or a file, retrieve the object from the id and get again the message, channels, guilds and the roles)
oh, so like a .json file?
They will work too
not if you want to have a good time, no
Well to testing json is good enough
json should only be used for data that doesn't require constant access
@placid skiff well I just simulated his situation got everything ok
Not in cogs but normal
@bot.listen('on_command_error')
async def command_error_controller(ctx: commands.Context, error: commands.CommandError):
print(error)
await ctx.send(f'Error lul')
return 'Some return whatever'```
It doesn't matter what error handler returns but typically it shouldn't return anything
you shouldn't encourage using it for testing because json-like databases are not more popular than relational databases
Also I have a script in place to make sure the bot never permanently goes down unless I tell it to, because I use Replit as my IDE
Btw how to store a list in sqlite (besides putting a string to there and splitting it)
you should really read this text to understand the implications of using json to store data in the case of a discord bot
Or even better a dict
I think that is not possible lol
Sqlite doesn't have such row types
@humble granite hold up check if you are adding the cog with error handler once
Maybe you've added it twice not sure if it can do anything about it
What db does then
Relative one
Not json-like
well what do I use instead of json as a database?
sqlite3
Good for starters
If you don't wanna learn sql you can use a wrapper, I actually have one published on my github (but its functionality is very limited) maybe there are other
Seems like postgre does
As I look at its codes they seem complicated but I should learn it most likely
Omg it can even store jsons inside
Postgre seems epic
how do I use SQLite in my bot
There is a package which turns python class into sql tables, i don't remember his name btw you add what database you are using and it does it automatically without you write any query
I can implement that thing by myself but thanks
I think that you and i watched the same tutorial xD
I didn't actually watch tutorials I read sqlite docs 
๐
You would have to learn about SQL a bit. Or you could be the first user of my package (maybe such ones and better ones already exist but idk), you may check it out here https://github.com/Exenifix/ExenDB
Why would I name it db
How can I make it so when someone presses a button, it checks if they send the message. If they didn't send the message, it privetly sends them a message saying that its not for them
i hope that makes sense
You mean make a button for specified person?
Alright first tell us what library do you use
yes
like discord.py or pycord?
Delete it there's token
And regenerate the token immediately
I mean delete the image from here lol
Those are 2 different ones lol
Just regenerate it
i think i use both... stuff from both work in my code
that's extremely bad, pycord is a fork, not an additional package for discord.py. you should only use one lib
ok nice
so can someone answer my question?
Can we see the code?
@frank tartan sorry, but I personally don't know about pycord. In dpy 2.0 and disnake you can overwrite interaction_check method for your class inheriting View
(please blur the token again while sending ss of code)
Like
thats how i am doing buttons
await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
Like this, maybe the same thing is in pycord
try statements must be followed with an except statement, u have no except statement and so it's giving an error
async def chan_reply(interaction):
await interaction_check(interaction)
await ctx.reply("""```
like that?
Nope lemme show you
class CustomViewClass(discord.ui.View):
... #init stuff and buttons
async def interaction_check(self, interaction):
#this should return True if the interaction author is valid```
i dont use cogs
It's not a cog ok
but it looks like cogs
That doesn't require a cog
It is a class
Do you know what a cog is?
not really, i just know that alot of ppl use them but i dont
Cog is a class but it is a different class lol
so would that replace what i currently have?
Cogs are just classes as Exenifix said, it's a subclass of commands.Cog and here we are subclassing discord.ui.View
ok
What do you currently have
I recommend you to check the examples in pycord repo
https://github.com/Pycord-Development/pycord/blob/master/examples/views/confirm.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/confirm.py at master ยท Pycord-Development/pycord
i have alot of buttons, i will show you one of them
msg_button = Button(label='Message', style=discord.ButtonStyle.green)
async def msg_reply(interaction):
await ctx.reply("""
---๐ ๐ฒ๐๐๐ฎ๐ด๐ฒ ๐๐ผ๐บ๐บ๐ฎ๐ป๐ฑ๐---
sendMSG <message> - has the bot send a message that you chose.
ssendMSG <message> - sends a message that you choose. (requires manage_messages permission)
msg_button.callback = msg_reply
view = View()
view.add_item(msg_button)
await ctx.send("What commands would you like to view?", view=view)
Oh lol
Look at those examples, custom views are way more convenient
;-; ok
i know about buttons
Buttons gud
Yeah self missing lol
why dont you subclass view ๐
View*
and yes
it was correct
it might return None or the connection
cuz this is what the tutorial i folllowed said to do
ik
how?
bad tutorial tbh
Follow example
it was the most popular tutorial i found -_-
well you see the else might not execute
so the function would return None
else it would return the connection.commit()
!e
print("Most popular" != "Correct one")```
@vale wing :white_check_mark: Your eval job has completed with return code 0.
True
Even python bot says 
mind linking the video ?
ah ic lol
i didnt save it
๐ณ
^ and by a lot
or would you
yeah i just did
๐ญ
i typehinted the discord.bot object as commands.object 

moving on
that isnt helping -_-
Seriously?
what do you need help with?
yeah i learned from those examples
howwww
its just subclassing a class lol
Now I have my own beautiful subclass that does everything I need
not better than mine tbh
;-;
please activate windows
LMAO
pretty easy and good
Lemao
h-how do you live with that shit on the corner at all times
i can't wrap my head around it
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
my ocd would never let me
ive been like that for like 2 years
idc about it, mainly cuz i use multiple screens
for the love of god use a MAS
me flexing my windows 11 rn
I tried to remove it manually but it came back
lemme grab my laptop and flex
i was forced to windows11
alr let's not delve too deep into off topic
Ok #Win11FlexGang
Yes
my nice view
Looks nice
those embeds are disgusting
cant do much about them tbh
yes you can
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'guild_id'
what can i do then
;-; i came with a question and now i have to re-do everything ;-;
discord.embed().set_image(url=None)
smh no need to set it on the var
!d discord.ext.commands.Context.guild
Returns the guild associated with this contextโs command. None if not available.
Has id
me with 2 monitors and a 3060๐ถ
well subclassing button is better for one button, if you wanted more than one you can subclass view
i have 2 monitors on my pc
Me with GT 710 
niceee
๐
where did i even use set_image ?
can you link a tutorial on yt?
i learn better from those
it was a example smh
dont think their is
;-;
why give me a example of something i didnt even use
you can use it with the footer
Hold up what
https://www.youtube.com/watch?v=kNUuYEWGOxA&t=170s this looks good
This is the Ultimate Python Guide on Buttons with Discord.py or Pycord. In this video, I talk about how to create buttons in discord.py or pycord and how to respond to button clicks along with everything about Views. After watching this you'll know everything about Buttons and Views in discord.py or pycord.
This video might also apply to other...
i've used more than one footer
Does it return the embed itself on call
THATS THE FUCKING VIDEO I WATCHED IN THE FIRST PLACE
Forgor
use it
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.

@vale wing heres the video
what they didnt isnt good practice tbh
From 16.00
imagine converting something like this applying their logic
???
I mean from 16.00 he tells about subclassing
lmao you want it to look like
Fluent-style chaining?
frick did i not watch teh whole video?
It is more of javascript and java
await interaction.message.edit(embed=discord.Embed(title="Mod helping command", color=Colors.gray).add_field(name="Banning",value=f'{prefix}Ban "{prefix}ban <@{BOTNAME}> reason"\n{prefix}pban `deletes the user messages and ban them` "{prefix}pban <@{BOTNAME}>"\n{prefix}unban "{prefix}unban <@{BOTNAME}>"',inline=False,).add_field(name="kick", value=f'{prefix}kick "{prefix}kick <@{BOTNAME}>"', inline=False).add_field(name="mute",value=f'{prefix}mute "{prefix}mute <@{BOTNAME}>"\n{prefix}unmute "{prefix}unmute <@{BOTNAME}>',
inline=False,).set_thumbnail(url=self.ctx.guild.icon.url))```
Btw have you ever seen discord bot written on java (it looks very ugly imho)
looks overcomplicated imo
totally readable
Java itself is good but discord bot written on java is ugly in terms of code
ikr
In terms of memory it might be slightly better tho
its not, one variable wont consume as much as you think
the heck is kotlin
programming language for the JVM
Language
not about storage but about style tbh
ah ic
Still it will consume some memory
But in this scale doesn't matter I agree
i mean, sure, separating this isn't gonna be any more efficient but
holy shit, that is some ugly looking code

Jetbrains uses it for their student programs
Just looked at kord wrapper looks good
Idk kotlin tho java only ๐
I tried to enroll before realizing I would reveal where I live
and that won't look good on my commits
I can probably persuade the headmaster to enroll at gunpoin-
yeah, kord is great
unlike jda

I made a leaderboard command with sqlite3 and am struggling to make it display the leaderboards per server/guild. Atm it shows a global leaderboard. Does anyone have any knowledge on this?
async def lb(self, ctx):
db = sqlite3.connect('kof_db.sqlite')
cursor = db.cursor()
cursor.execute(
f"SELECT member_id, wallet, bank from main ORDER BY bank DESC LIMIT 5 ")
result = cursor.fetchall()
embed = discord.Embed(title="Leaderboards", colour=discord.Colour.orange())
for i, x in enumerate(result, 1):
embed.add_field(name=f"#{i}", value=f"<@{str(x[0])}> with :moneybag: **{str(x[2])}**",
inline=False)
await ctx.send(embed=embed)
cursor.close()
db.close()```
Depends how you store them in your database
It is more db related question but let us see anyway
@prime marten what the database looks like
why f-strings?
i only recently added the guild_id column so this might be a problem
Only one table?
im new to this ๐ฅฒ
how do you find a tables data like that im not sure
I mean I store user and member data in separated ones
hmm
Quick tip, you can select total funds like this iirc
SELECT wallet+bank AS money ... ORDER BY money DESC```
Nice
really
real mature
oh dang my IDE has a built in database
well that makes things easier
Can someone help?
If you Union it with str it should be able to accept any input.
Why do you want to do it like this though?
Ah so, my ticket command has 4 options. open, close, add and remove with add and remove both accepting a discord.Member object while open and close don't however if you add another argument to the open and close, since they are all part of the same command (which is what I wanted), it errors because it isn't a discord.Member when I preferably just want it to ignore that argument since it's not required for those two.
I mean unless there is a way around this? But I've just had no clue, only thing I could come up with.
yeah there is a better way. sounds like you want to have subcommands
Make a command group, and then add commands to that group
hello i have a problem this is the code:
import discord
from discord.ext import commands
import test
cogs = [test]
client = commands.Bot(command_prefix ='!m',intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup()
client.run("TOKEN")```
This is the error
```Traceback (most recent call last):
File "main.py", line 6, in <module>
client = commands.Bot(command_prefix ='!m',intents = discord.Intents.all())
AttributeError: module 'discord' has no attribute 'Intents'```
discord is somehow undefined
idk how
import intents
Docs don't seem to have a good example of this. basically something like
@commands.group()
async def foo():
...
@foo.command()
async def open(...):
Thanks, I'll have a try!
what are command groups for?
For nesting commands
ah ic ty
You are likely using an older version of the library
Try updating it
i am using replit
Is it not possible to update dependencies on replit?
i think they are latest versions
Do print(discord.__version__) what is it?
wait replit is so dog water that my system crashed for stopping the program
but free host
1.7.3
and i still have the same error

I don't know. That doesn't make sense.
fr
i tried running it a couple of times
but same thing
@slate swan check these files maybe you should edit them, haven't ever used replit but seems like the issue is there
what can the issue be
ooooo ok
Also here
ok
@bot.event
async def on_message_delete(ctx):
embed=discord.Embed(title="{} deleted a message".format(ctx.author))
embed.add_field(name="What the message was goes here" ,value=f"{ctx.message.content}", inline=True)
channel=bot.get_channel(930546282097938492)
await channel.send(channel, embed=embed)
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "D:python\Logs\bot.py", line 24, in on_message_delete
embed.add_field(name="What the message was goes here" ,value=f"{ctx.message.content}", inline=True)
AttributeError: 'Message' object has no attribute 'message'
help?
!d discord.on_message_delete
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
ctx.content
^
how do put the member avatar from above in the title ?
as in the screenshot?
!d discord.Embed.set_author
set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
This ^
thanks
with?
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
^^
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
With sub commands I would have to define a function 4 times right? I can't like make it so the function is accessible by all 4 sub commands without being fully global.
How long does it take to answer someone in #web-development
can you give an example
I'm not sure of any scenarion where you would need to define the same func 4 times
I used to use the method of creating subcommands via a single @client.command() and if statements from the arguments passed however since the subcommands are each in their own function async def sub_command(ctx): for example, I wouldn't be able for all the sub commands to use the same function will I and that's without making it completely global for the whole code.
I don't really know what you mean
you wanted to invoke a subcommand from the main command?
there's a commands.group decorator too, for making commands and subcommands, by the way
In Disnake params would it be possible to disallow certain characters?
maybe a custom converter
Good idea, i'll start trying right away.
ping me if you're stuck
๐
so ```py
@bot.command()
async def whatServer(ctx):
id = ctx.author.id
if id == 828182019841327115:
le = len(list(bot.guilds))
em = discord.Embed(title="servers", description="", colour=ctx.author.color)
re = list(bot.guilds)
for i in range (le):
em.add_field(name=str(i),value=re[i]["name"],inline=False)
await ctx.send(embed=em)
anything wrong in my code?
dpy doesnt have a law lol hes just breaking yt tos which if you break yt tos you break discord tos
ther, fixed
lol
can you post the full traceback
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\thosiba\PycharmProjects\main.py\main.py", line 119, in whatServer
em.add_field(name=str(i),value=re[i]["name"],inline=False)
TypeError: 'Guild' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\thosiba\PycharmProjects\main.py\main.py", line 53, in on_command_error
raise error
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thosiba\Downloads\d-bots\lib\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: TypeError: 'Guild' object is not subscriptable
@full lily Not possible :( Discord API only allows certain types so no custom checks to deny them from using the slash command. You can manipulate the outcome with the converter but what they inputted will still be send since it does count as a string.
re[i]["name"]
re[i] is a Guild object, the attributes are accessed like this re[i].name
can you try this
lemme try
fk, now lag
Yes but you can raise an error to stop command invocation
niceeeeeee it works, tysm
I have no idea how to do that.
Yeah
I got a regular check now with regex
But I want their Discord to shake with shame if them inputting it wrong.
Converter was worth the try though
So the command will have to go through either way, but you can tell the command what to do with the arguments
does this work?
This works flawlessly
Why wouldn't it?
So what did you want to do different then
how to fix discord http generator
Hmm?
Well so ```py
if characters := re.search(ILLEGAL_CHARACTERS, package):
It's not broken i was just looking to enhance it :3
im gonna give u 300 proxy if u help me
300 proxy?
ye
I don't know what those are and no
The heck is that
aight
Aren't proxies like 127.0.0.1
idk
~~Traceback (most recent call last): File "C:\Users\home\Desktop\DiscordHTTPGen-main\main.py", line 1, in <module> from hcapbypass import bypass File "C:\Users\home\Desktop\DiscordHTTPGen-main\hcapbypass.py", line 4, in <module> import httpx ModuleNotFoundError: No module named 'httpx'~~
Bypass HCAPTCHA purely based on http requests Works for discord dosenโt create locked accounts :))
No.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
ok
Why are people abusing Discord 

Cuz u can join many servers and meet alot of people unlike other apps they have DMs only
๐คท๐พthats the only reason ig
With valid reasoning, it's absurd bigger servers need bots to prevent nitro scammers.
@long rockhi, since we don't allow help on projects like this (see rule 5 above), will be closing this thread
๐they're using bots to grow their community
Mina :3
How've you been?
async def stat(reason):
r = requests.get(f"https://api.hypixel.net/player?uuid={reason}&key=0f4686d5-5696-4b6e-843e-79932a76fbdc", headers={'content-type': 'application/json'})
print('line one called')
print(r.json()["player"]["lastLogin"])```

It's recommend to use Aiohttp
why ppl scam nitro
You can't do nothing about it if they dm people and you don't know
Requests is blocking
what is aiio http
Mina casually deletes discord bots
Use aiohttp
do i just do import
aiio
Then import it
Instead of requests
hey guys I am having a trouble with my bot again
why doesnt this work? it should delete messages if they are all caps
Basically anywhere you have requests, you should replace it with aiohttp
it used to work but doesnt anymore
Mmm errors? Is there any error
doesnt isupper()
make message content all caps?
!d str.isupper
str.isupper()```
Return `True` if all cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) in the string are uppercase and there is at least one cased character, `False` otherwise.
```py
>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False
No it returns a bool
ah ic
thats .upper()
yeah sorry got confused
uhh i didnt get any response from the bot
Mmm try message.content.isupper() == True since isupper returns a bool
changed code to this
Oop wrong reply
for me?
Wouldn't make any sense
hm?
dont know ๐คท๐พ
!e ```py
if "TEST".isupper():
print('true :3')
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
true :3
Please print message.content and paste it here
Im on phone ๐

Even if i was working on my phone i would work on my vps
!e ```py
if "TEST".isupper() == True:
print('test')
@slate swan :white_check_mark: Your eval job has completed with return code 0.
test
Then it might work๐ค
You are comparing if true is true
Wait
@slate swan This also works
!e ```py
if "TEST".isupper() == False:
print('test')
else:
print("sks")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
sks
it works ๐
!e ```py
if True is True and "TEST".isupper() is True and True or True and True:
print('Doesnt matter')
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
Doesnt matter
!e
if True == True:
print("yes")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
yes

Lmao
!e ```py
if False == False: print(bool("yes"))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
True
I think you got the point lol
how do i check when the bot closes?
Ig
"closes"?
like py @bot.event async def on_close(): print("bot_closed")
like when i stop the program or do await bot.close()
I've been trying and looking for a while on how to make a ticket system using buttons in discord.py without cogs havn't been able to figure it out. if anyone does lmk or dm me plz
!d disnake.on_disconnect
disnake.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_connect "disnake.on_connect") call.
alr
!d discord.on_disconnect
discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_connect "discord.on_connect") call.
Same story
It's better to start working on it :3
can so,meone help me
1st line is getting called
second line isnt
and when i just do print(r.json()) it returns with malformed uuid
okay sure
also i had to go to sleep yesterday so thats why i didnt respond if u tried to reach me
but ctx is not accesed by pylance
should i do await ctx.send
what?
i'm telling you to add context to the list of arguments on the function definition
otherwise you're passing ctx as reason and your request returns "malformed UUID" because of that
that's what you want, isn't it?
nope
that's an unix timestamp
someone know how to make a bot send an email
it's written in your code though
my discord bots ping is 0.04 but is stupidly slow. will this be a problem with my host?
use the datetime module with utcfromtimestamp and strftime
Email? What..
ah shit I gotta go to the bathroom
print(f"<t:{r.jaon()["player"]["lastlogin"] }:d>")
sure but how would i do that
why do we needed to know that
40ms is pretty decent.
datetime.utcfromtimestamp()
<t:1641889126926:R>
no i mean like it is stupidly slow. but the bot latency from the api is quick. so it must be my host?
Might not be a valid date
@cloud dawn
Wdym slow?
There is 2 f
that was baby criminal oops
And
where to the player and ;ast login
like this print(f"<t:{r.jaon()["player"]["lastlogin"] }:d>")

should i try it
Use aiohttp unless you want your bot freezing when someone runs the command
We said that 20 min ago smh
i was pretty straightforward
bot didnt respond
He's not listening I guess
no i tried it
ยฏ_(ใ)_/ยฏ
You most likely did it incorrectly
๐
This server doesn't allow hiring of any kind.
no @slate swan just that year is wrong
that has nothing to do with how to make a bot that sends emails
how do i fix that
I said this wasn't a valid date 5 min ago
@client.command()
async def email(ctx, sender, recipient, subject, *, body):
global address, password
if "`" in body:
body = body.strip("`")
message = MIMEMultipart()
message["From"] = sender
message["To"] = recipient
message["Subject"] = subject
message.attach(MIMEText(body, 'plain'))
address = sender
dm = await ctx.author.create_dm()
await dm.send("Send me the password for your email.")
msg = await client.wait_for("message", check=lambda m: m.channel.type == discord.ChannelType.private)
password = str(msg.content)
embed = discord.Embed(title=f"From: {sender}", discription=f"""To: {recipient}
Subject: {subject}
Body:
{body}""", color = discord.Color.blue())
await ctx.send(embed=embed)
๐คท๐พwell
i changed requests to aiohtttp
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
Not correctly
Everyone ๐ง
i will listen to u the whole way
ok then
do u want me to change it back to aiohttp
current code
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
i mean my global statement is necessary
They are never necessary.
Nice job leaking your key ๐ง
no ill reset it ofc
i use the global variables outside of the func
anyways the api key literally comes with no powers except from veiwing stats
u cant really do much
Send me the password for your email. kinda sus
with that key
ik but
its just for me and my friends
and its a dm

pls no fbi
They have a key for a reason
Im using pymongo 
ik ill reset it
There is most likely a punishment for spamming requests
spamming reqs?
Not async ;-;
Ye ik
Special.. punishment..
๐คจ
if u really want me to reset it ill do that but anything else u can help me with
Most likely ratelimit (i hope)
Imma search up for motor docs๐ญ
as you can see, the code has no way to keep the persons password
!pypi motor
Non-blocking MongoDB driver :3
I could overwrite the str function to just fetch the password lmao
Should I ask for help with discord bots here or go to a help channel?
here
@slate swan did you sleep
Okay, so I was wondering if there is a way to change everyone's nickname on the server all at once but choosing a random name from a txt file
Oh seems like I accidentally entered the wrong class
async def stat(ctx, reason):
r = requests.get(f"https://api.hypixel.net/player?uuid={reason}&key=api", headers={'content-type': 'application/json'})
await ctx.send(f'<t:{r.json()["player"]["lastLogin"]}:d>')```
9hours yes
This is how to get rate limited 101
there reset it
I should be in cogs
can u pls help now
๐ถ
good that makes one of us
ikr
I slept for 3 or so hours
Any reason you're not using a wrapper?
im using disnake is that a wrapper
Hypixel api wrapper
Discord
There has been a desire from members of this forum for a quicker and more interactive way to communicate than via the forums. It is my recommendation you use this Discord server for these types of discussions. Note this is an unofficial Discord, unaffiliated with Hypixel.
Wrappers
This...
because they don't need it for hypixel? they want the one request and it's perfectly fine to not use a wrapper
Just let me know if this is a possibility I can figure it out myself I just need a little nudge in the right direction
you don't need to use a wrapper for everything..
yeah, it's possible
oof
im not using any hypixel wrapper
No offense to them but this seems complicated for them
imo it would be simpler to just use a wrapper
well if you know of a wrapper it's possible to compare... but otherwise..
Awesome! thanks for letting me know.
not at once, no, but doing that is certainly possible
which wrapper should i use then
Just sent a list
@green bluff
Okay
so do pip install the wrapper
Yes
arkflame72/asyncpixel* Lightweight. One commit in the last 30 days.
Snuggle/hypixel.py No commits in 2 months.
SomePr0grammer/aHypixel
Kanin/PyPixel No commits in 11 months.
MyerFire/hypixelaPY No commits in 3 months.
xMicky24GIT/pyhypixel No commits in 13 months.
TheLegendOfKitty/snakepixel-beta No commits in 7 months.
SlashNephy/Hypixthon**r these the python wrappers
isinstance will check if both objects are of the same type, so your check here will always return true
install one of thesse?
Read what was said above that table
so do i get the darkflame one
you can just do return ctx.channel == channel
!pypi asyncpixel
@final iron you're probably just getting him into more trouble with this wrapper, it's async and he will need to adapt for that
Ye
He would need to adapt his current system to async anyway
the date is slightly wrong tho
How wrong?
it's your responsibility to help him then
very wrong but when i hover my mouse over it its the right date
what do i do with this
the time is right
the one converting that unix timestamp to a date is discord, you can't control it
Did you leak your key again?
omg
ur done ๐คฃ
just pls tell me whats worng

๐ง
you can
the Unix time needs to be in scale with 1/1/1970
epoch iirc
i'm not sure what's wrong then
Same here 
bruh why does this always happen to me
it even happened to my giveaway command never responded till like an hour of fixing
google loves to bother me
let my program work pls
you literally are meant to work with this api
yk what, i should stop trying to do this.
i feel like im gonna lock myself out of my account
my ping is averaging at around 500ms
my host averaging at around 14ms
is there a solid way to fix. or possible reasons for delayed response. other than discord api being globally slow
maybe your wifi is slow
my ms isnt that high
it really depends on allot of stuff
and i have terrible wifi
im pretty sure it doesnt depend on personal wifi
any game i join has at the very least 500 ping
and my wifi isnt slow
???
ok what would you consider slow wifi enough to affect my bots ping?
just because this is slowest ive seen it for about 3 years
high traffic will
i dont host this bot my self though. it is slow in response no matter who uses a command
of course
Idk wut to say but wut host you're hosting ur bot
and in users as well?
no its only for a 14k server
14k is quite a bit
also the amount of code you have in your program can cause it to move slower than usual
the host isnt a problem as i said the server is averaging a 14ms response time
might be it if true
also if you are opening a bunch of webpages over and over again
one cog file has 3k or so lines of code
webpages no there is a few api requests looped per second
not to discord*
well idk. When heroku's dynos about to run out the bot comes slow
i got an odd question for someone good with APIs
wdym by odd and is it related to this channel
Yes
then send it
Ill explain after dinner
Who do I speak to about suggesting another bot hosting service?
to add to the list
if u want a free one the best one is heroku, its actually easy to use aswell and if u need help setting up i can help u ive set it up aswell
That's not what I meant.
o ok
I found a bot hosting service that's not on the list and want to suggest it be added to said list
what list
ah
ok
I imagine that discord and its bots can handle utf-8 characters right?
yes. that do be the standard for most platforms.
Whatโs it called 
pebblehost
I've been using it for a few weeks for my bot and it's quite reliable and fast so far
Is it a vps or something?
Or is it just some panel you get to upload files onto and what not.
Not a VPS. Just a panel to upload bots. it has a few features like MySQL etc
i can send screenshots if you want to look?
inb4 Pterodactyl panel
Thatโs probably what it is tbh.
Called it




