#discord-bots
1 messages · Page 728 of 1
the cooldown
guys which is better disnake or hikari
How would I do the following?
“””
if (role is higher than member):
blah blah blah
“””?
Or would I have to list every single role higher than member?
ctx.author.top_role.position
if ctx.author.top_role.position:
blah blah blah?
Cuz the userid isn't in a function that define ctx
Userid is undefined
Now I defines userid and ctx is not defined
Because ctx is not defined..
guys which is better disnake or hikari
Ik
That's not how you do it, you need to have a command.
Use both of them, and compare yourself. It's personal preference.
Make a command and it's automatically defined.
what's the most efficient way to make a global variable for returning an emoji?
they say the bot var is the best
@bot.command()
async def command(ctx):
# ctx is defined
Well not for the use case of userid
Lol ok
Then I define those var inside an async function?
How do I call them when I need
Just await funcname()
?
Make a new file called like emotes.py, save your emotes as string values and import it in the other files you need.
well it's only two I can think of but I was talking about the method to return them
I need to make the emoji var global?
You don't need to, just make a new variable like normally
emote1 = "<...>"
Then you import the file where you need the emote and you can use emotes.emote1
would it be as something like
def emoji():
x = bot.get_emoji()
return x```
or would it be as a bot variable under initializing the bot construction, or maybe even on `on_ready`
That's a pretty much irrelevant function.
Just use bot.get_emoji in that case.
Creating a new function that does exactly the same as another function is pretty much useless code.
Where do I put that?
Just like doing
def print_something(str)
print(str)
is discord.Role a type?
but then I don't have to write bot.get_emoji(emoji ID) many times in the code, I can just use emoji
!d discord.Role
It's a class.
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
no like would it work if if type(msg.content) == discord.Role: ... or did i forget basic python
Well no you can't really, since you still need to provide an ID.
!d instanceof
No documentation found for the requested symbol.
god
oh i know isinstance
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
Yeah this
haha guessed it before you! x]
i meant like this
def emoji():
x = bot.get_emoji(1234...)
return x
First argument: Your variable
Second argument: The class
Then what's the point of the function?
You're just overcomplicating things.
I just want to define something like succes_emote so that I can use it anywhere in my code without having to keep write bot.get_emoji for each command
And you want to send that emote sometimes I guess?
you took the words straight from my mouth.
yeah, like with embeds
Then just make a new file which contains the emote in format <...> saved in a variable and import it where needed.
guys which lib do u use?
As I already said, it's a personal choice.
Try libraries out and find out which one is the more convenient for you.
well I guess I can leave out the other file, since it's mostly two emojis ( a success emote and error emote) so I will just use the variable but would it be better to define it on the on_ready or seperately as another var?
in my opinion, i like disnake since it has timeouts 😍
ngl @slate swan thats genius
ah so that is the most efficient way of doing it?
but why not a star import?
hey wait a second just use variables x]
To prevent confusion with other variables, in case you name them similar.
I guess? You're just importing the variables and using them.
just name it daheudfshdkfshksfdhfsdk and you have no similarities 👍
dw code completion will get it for you
I smell enums
Enums are not per default in Python and the alternatives are gibberish. Whereas enums are not convenient for this use case.
Now for just 2 emotes, I'd guess you can just put them normally where needed without having to add variables and therefore would prevent overcomplicated stuff.
But he has constant values for these names
Then why using enums when your can make simple variables?
And they're under a "category" of emotes
And using enums, that are not per default.
if your using a module for that sh*t then why not put it inside a class to avoid similarities?
Yeah you don't have to use enums
how do u put perms in ctx.guild.create_role(perms=...), is it just a list like:
[manage_messages=True,...]
iirc its a discord.Permissions obj
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.update "discord.Permissions.update").
well,
async def success_emoji(ctx):
emoji = bot.get_emoji(840920214035628082)
return emoji
@bot.command()
async def test(ctx):
await ctx.send(success_emoji)
this sends <function success_emoji at 0x0000013F840D8670>
call the function
call the func
async def success_emoji(ctx):
emoji = bot.get_emoji(840920214035628082)
return emoji
@bot.command()
async def test(ctx):
await ctx.send(success_emoji(ctx))
Why adding a ctx argument when it's not used?
Remove the parameter from the function and remove the argument.
And I think it will send the object and not the emote.
So you'd want to str() it, or use f-strings.
now
async def success_emoji():
emoji = bot.get_emoji(840920214035628082)
return str(emoji)
@bot.command()
async def test(ctx):
await ctx.send(success_emoji())
does <coroutine object success_emoji at 0x000002726038D1C0>
I'm assuming I missed an await, but where?
emoji = await success_emoji()
await ctx.send(emoji)
str(emoji)
so I put it when returning emoji and also when sending it?
Only when sending.
This ^ and add str() when sending.
They are already returning str(emoji) in function
oh, okay but then is there a way to be able to do it without having to keep awaiting it in each command?
Oh yeah, haven't seen they changed it, my bad.
Nope
Just send the emotes like that: !python in your embed.
oh...so then I guess I'll use a variable instead of a function
Especially if you only use 2-3 emotes.
haha i see
I gave my credit card to Aws and they said they'd activate my account within 24 hours. Its been 48 hours since then
wrong channel..
rip but not the right channel
For hosting a discord bot
you'd need help with aws, not discord bots
I don't need help I was just telling
just a question why import discord as disnake
Cuz why not lol
can i find the argument was was missed on the missing required argument error handler
nevermind, got it
<t:epoch:format>
To get the epoch, you can use something like this: https://www.epochconverter.com/
tyy
Here are the different formatting methods for the format part:
No *
It means it's default
So you can remove it along with the "f"
<t:1641370396> => <t:1641370396>
But I really failed to understand how to get the epoch
i need a event which detects audit log action of webhook create and bans the user and deletes the webhook
!d discord.on_webhooks_update
discord.on_webhooks_update(channel)```
Called whenever a webhook is created, modified, or removed from a guild channel.
This requires [`Intents.webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.webhooks "discord.Intents.webhooks") to be enabled.
i know bro btw i couldnt make the code
@client.event
async def on_webhooks_update(channel):
try:
guild = channel.guild
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.webhook_create):
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Webhooks")
await i.target.delete()
except:
pass
this code is not working
well since you just pass the exception , you won't get where the problem is
what to do then
Remove the try except , and see what error you get
!d discord.TextChannel.guild
Alr
@client.event
async def on_webhooks_update(channel):
guild = channel.guild
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.webhook_create):
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Webhooks")
await i.target.delete()
```
this?
Yea try running this and see the error
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 326, in on_webhooks_update
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Webhooks")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 2026, in ban
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Ignoring exception in on_webhooks_update
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 326, in on_webhooks_update
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Webhooks")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 2026, in ban
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
bruh
The bot itself is missing permissions
^^^
it has permission of admin
Since you created the webhook , and your bot cannot ban u
Send the link in dms
ok
await i.target.delete()
AttributeError: 'Object' object has no attribute 'delete'
what to do
oh , try py webhook = await client.fetch_webhook(i.target.id) await webhook.delete()
ok
where to put it before async for i line or after it?
Last line
ok
wow what the heck speed of webook deletion spendid bro working
guys how can i make a slash command in cog using disnake ?
Morning
morning dekriel, but anyways i tried figuring out how tf to use permission names
like manage_messages, manage_channels but then a super long name like manage_emojis_and_stickers or view_audit_logs
they are listed in the api reference somewhere
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.update "discord.Permissions.update").
class disnake.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions "disnake.Permissions") similar to [`update()`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.update "disnake.Permissions.update").
Same for disnake, just some different names and new permissions due to updates.
# Custom help command
@client.command(name='help')
@commands.cooldown(1, 30, commands.BucketType.user)
async def help_command(ctx):
embed = discord.Embed(title='3P PIE HELP CENTER', description='These are all the commands available on this bot.', color=discord.Color.gold())
embed.set_thumbnail(url=bot_logo)
embed.set_footer(text='There is no specific help for every command, it wastes time and the name of commands are related to their functions.')
embed.add_field(name='Help Commands', value='`help`', inline=False)
embed.add_field(name='Coming Soon', value='`support-server`', inline=False)
msg = await ctx.reply(embed=embed)
await msg.add_reaction(trash_emoji)
def check(user, reaction):
return user == ctx.author and reaction.emoji in [trash_emoji]
user, reaction = await client.wait_for('reaction_add', check=check)
if str(reaction.emoji) == trash_emoji:
await msg.delete()
await ctx.message.delete()
Please tell me why it don't delete the message on the reaction of delete emoji 😭
Setting a command signature in the command decorater doesn't change the error.param of a command. Is there any way around this?
What is trash_emoji?
Its a custom emoji
Well
It's pretty simple.
You've defined user, reaction
But the event gives reaction, user back
!d discord.on_reaction_add
Oh
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
It's exactly the same as you have right now.
Just replace
user, reaction = await client.wait_for....
to
reaction, user = await client.wait_for....
Same in your check function.
Did
def check(reaction, user):
return user == ctx.author and reaction.emoji in [trash_emoji]
reaction, user = await client.wait_for('reaction_add', check=check)
if str(reaction.emoji) == trash_emoji:
await msg.delete()
await ctx.message.delete()
def check(reaction, user):
return user == ctx.author and reaction.emoji in [trash_emoji]
reaction, user = await client.wait_for('reaction_add', check=check)
if str(reaction.emoji) == trash_emoji:
await msg.delete()
await ctx.message.delete()
Indentation is completely wrong, please take a look at it again.
STILLL DON"T WORK
!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
def check(reaction, user):
return user == ctx.author and reaction.emoji in [trash_emoji]
reaction, user = await client.wait_for('reaction_add', check=check)
if str(reaction.emoji) == trash_emoji:
await msg.delete()
await ctx.message.delete()
@slate swan
This is my code
Pls someone hellp
str(reaction.emoji)
u were already told your indentation is wrong and it clearly is...
In your check function
No, indentation now is correct.
oh, i didnt scroll down when i type that whoops
help
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
i dont understand :)
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
how does one get the argument that raises BadArgument?
did you even read what I asked?
exception discord.ext.commands.BadArgument(message=None, *args)```
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
like for example MissingRequiredArgument.param returns which argument was missed.
How do I get which argument raised bad argument
it doesn't seem to have any attributes
unlike BadUnionArgument which does
makes no sense to me
maybe if you use typing.Union on every argument then you can get it from BadUnionArgument 🤔
hey i want create a event in which if some person send embeds or someone has streaming status then hw would get banned as selfbot user
I do not think that you can do that with embeds, since the embed could also be a youtube link or smth
btw i need only embed responder
in which case you'd need to do some logical handling
like?
if there's an embed AND no url, then ban
yep i want its code
btw i couldnt make it
i tried bro btw i dk how to make it
i am stuck at
@client.event
async def on_member_message(message)
use on_message
i dont want to ban bots
not on_member_message lmao
wow
if message.author.bot, then return
what
if len(message.embeds) ...
if len(message.embed) >0?
well the >0 isn't even needed
because if will return false if it's 0
and true if it's 1 or more
no
?
nothing's needed
only if len(message.embed)
ohk
@client.event
async def on_message(message):
try:
if mesage.author.bot:
return
if len(message.embed):
if "https:" in message.content:
return
else:
await message.author(reason=f"ANTI SELFBOTS")
this?
you don't need the try
wait except:
pass
ya
and it's just await message.author.ban(...)
btw what about checking streaming or watching status of users
let's see if it works
hm
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
is there anything about presence?
ohk
even the one you need, where someone changes status
and the classes
!d discord.Status
class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") ‘s status.
Code:
while not client.is_closed():
status = random.choise(statuses)
await client.change_presence(activity=discord.Game(name=status))
await asyncio.sleep(10)
client.loop.create_task(ch_pr())
Error:
Traceback (most recent call last):
File "main.py", line 41, in ch_pr
status = random.choise(statuses)
AttributeError: module 'random' has no attribute 'choise'
wait I'm pretty sure there was a streaming status
can't see it now
choice not choise @craggy cloak
Thx
Yeah it is a test maybe i will do it every 30 seconds
that still seems much
Is that to much?
shrug
I'm and expert at Pycord
nice
hey for final thing i just need another cmd
@client.event
async def on_channel_create(channel):
i want to make an event which will delete channels which are multiply created in less amount of time
like 500 channels in 1 sec threaded
!d discord.on_guild_channel_create
wow
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
i do not know 
how would you even create that many channels
that's discordly not possible
@client.event
async def on_guild_channel_create(channel):
try:
guild = channel.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_create).flatten()
logs = logs[0]
reason = "Channel Created "
if client.user.id == logs.user.id:
return
await channel.delete(reason="R-Dynamic PROTECTION auto recover")
await logs.user.ban(reason=f"R-Dynamic Protection System")
except:
pass
``` this is the actuall code btw it cant del channels created by threaded nukers like 500 ch in 1 sec
he simply ignores actions
threads bro we r nukers we create that with allacrity proxie and thread nukers 110 bans per second spped
<@&831776746206265384> I don't think this is a good behavior and don't think the person has good intentions either.
bro i am actually working on antinuke bot
ye
to protect discord against this
!rule 5 @light violet we're not going to help you with a nuke bot. stop.
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
nukers i left nuking 1 year ago my id was banned
Not what your message says though?
bro i was asking how to stop a nuker who creates 500 channels in 1 sec
threads bro "we r nukers" "we create that" with allacrity proxie and thread nukers 110 bans per second spped
@slate swanread above
"We" implies you.
yep btw actually i am working on antinuke now
why would it be a nuke bot if we just put self bot defense in it
not for nuke
Then "we", which implies you, are "nukers".
i dk bro some bad peoples nuke
u should read above to know topic of discussion
I'm just quoting from your message, maybe you wrote it in a way you didn't wanted to
My report only refers to this single message.
actually
you pinged all mods because of a message
u should cuz this may harm someone
Someone asked how it is possible to create multiple channels in a few seconds, you said "we are nukers". The "we" includes you.
Not how, read carefully.
How it is possible to create that many channels in a few seconds.
okay let's stop
lawl
And they said "we are nukers", so pretty self explaining.
Now I'd suggest to leave it behind and move on :p
makin an antinuke bot
bro the topic was than i wanted a script so that we can del channels created by threads and he asked how one can create that in seconds so i made him understand the algorithm so that he could help not with a bad intension
Again, I was only quoting your message saying "we are nukers".
intension was diffeerenti nieghter i came here for nook source
we r humans not bots so we r pinging a msg
without knowing reason
i think u r a human too
back to topic?
what does logs even return
@light violet what ya need?
hey i am making an event which will detect threaded actions and del channels created in seconds like 500 channels in 1 sec and del them all without ignoring a single channel
like recovery of server
i dk thats what security bots are made for in case id is hcaked of admins
even if he has permission and does this, the bot deleting 500 channels is gonna ratelimit it instantly
and server in danger
So,bassicaly check if channels are created and count them,if too many channels are created(for example channels_created > 5) performe action,idk whats so complicated there?
If you are worried about this happening to your server, just force every channel creation to be done via the bot. So it can limit if required
clever
yep btw how to make it i dk
bro discord rate limits nieghter bans nor anything btw only webhook creation and ch deletion
and nothin else so threaded nukers nuke server easily
Hmm,i mean i have you what ya gotta do...i am not sure how it will look in code
replace limit=1 with limit=5
and if it's all channel create events, you do what you have to
@clieant.event
async def on_guild_channel_create(channel):
try:
guild = channel.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_create).flatten()
logs = logs[0]
reason = "Channel Created "
if client.user.id == logs.user.id:
return
await channel.delete(reason="R-Dynamic PROTECTION auto recover")
await logs.user.ban(reason=f"R-Dynamic Protection System")
except:
pass
actuall code and it need edit it dels only actions taken by user not threaded bots it would ignore channels craeted by thread
What you mean by thread?
for max security cant do it
google it lmao
multiple channel like things controlled at same time
fastesr than u can imagine
Ohh,i tough some shit with THREADS as module...
one blick server trashed
Not sure tbh
such powerfull
I mean, threading doesn't stop ratelimits
You'd need multiple accounts anyways.
And as Griff said, Limit channel creation to the bot only. Then less to worry about.
Prevention is probs better than trying to revert changes
umm hi
can someone help me in #help-corn ?
Well then don't create a server at all if you're so worried.
Or give the ownership to an account you never use and will never use, and have a very long and random password.
remember to use your 2FA 
Doesn't prevent token leaks though.
Which is what people would use to raid using the owner account.
But yeah as you said, prevention is better than revert.
Probs best to move back towards the topic of bot creation for Discord. Kinda moving offtopic
Yup
Since Discord.py got deprecated, I aint even looked into making Discord bots.
What is the best framework/package at the moment? In your opinion
disnake
disnake is probably the most used and popular one with updated features.
I'll take a look at their features page
I'd go for that, most of the others are either half-baked or not updated.
not for selfbots
it's the same as dpy
with slash commands and buttons
which is against ToS
It's a discord.py fork, so the code is quite simple to migrate. (If you had a previous bot of course.)
huh
caught a tos breaker in the act
@slate swanselfbots can do that without rate limit
experienced
Every account has rate limits.
Try it yourself :p
my server got nuked by that
You will get rate limited.
i dont think so by server got trashed by my frnds 3 times
Same for sending messages, adding reactions, etc.
bruh.
I do think so, take a look at the Discord API documentation.
Can we keep it on topic to Discord bot development
they aren't gonna stay ratelimited for weeks on weeks
@slate swanit did happen bro
You know you don't need to ping me in every message right? 😅

i know bro btw asking for u i want to make dc a better place and create the best antinuke possible so that we could sleep happily by trsuting admins
And has the same features as discord.py had and with the new components that weren't in the version 2.0 of discord.py and slash commands
anti-nukes = easy
You can't compare a library with a programming language.
i have one, fastest ttb was like 0.2s
no shyt
Let's not come off topic again?
okay we are heavily off topic
how to make threaded antinuke my frnd eagle made his new darkz security which stops threaded bans in seconds fastest bot ever seen what is its algorithm
my friend
How about you ask them since it's your friend?
it is released on yt bro
means not shyt
the vid of test allacrity vs darkz
Videos can be easy to fake if you know how your bot handles things.
dms
he invited me to the test server i saw the audit it was real
Anyways, you asked how they did it; then ask them since it's your friend :p
wanting to make an antinuke bot
❌ help him
✅ accuse him of nuking
Lmao
@velvet tinsel why

also this isn't relevant to discord bots
thanks a lot
?
🤔 ok
there is nothing like set_slowmode on a TextChannel, right? You have to edit the channel to do that
correct
Hello! I'm wondering which library is better: Nextcord, Pycord, Enhanced-dpy?
I'd say nextcord, based on what people told me.
Nextcord
But there is this new one called Pincer. It looks very promising
It’s still in alpha stage I’m pretty sure though
Yeah, heard of it. Doesn't look that bad, would need to see its performance, features, etc.
Once it's out of alpha, since alpha versions are known to be less stable and performant than official releases.
yea
!pypi disnake
Why it's better than other libraries?
it just is
its got better syntax
better maintainers
better collaborators
better owners (we love eqeuenos)
better updates
better community
better consistency
Hmm.. relax. You are a fan, that's obvious.
everyones a fan
Obviously not the people asking why it's better.
everyone inthis channel loves disnake
Debatable
non-debatable
Here's another stupid question: How many changes in the code would one have to make if they switch from Discord.py to disnake?
A lot?
well
does your code use dislash
if not, all you have to do is ctrl+r every word discord to disnake
and you're done
sorry for off-topic but i need rlly quick help pls friend and dm


Wow. Switching to it rn
Well, is there any objective arguments?
If you do this, you have to be careful about certain things that you might not want to be changed being changed from discord to disnake i.e the invite for your bot
Yeah, I'll be careful
You should have gotten a response now ^^
you can use the message.attachments property
!d discord.Message.attachments
A list of attachments given to a message.
ty
wait @little ether
nvm how do I check for a gif in that attachment?
there isnt a gif method or anything
is...
here's an example
for attachment in attachments
if attachment.filename.split(".")[1] == "gif":
# do smth
appreciate it bro
how do I get the url?
for attachment in message.attachments:
if attachment.filename.split(".")[1] == "gif":
gif_embed = Embed(title="random gif", color=0x0f0f0f)
gif_embed.set_image(url=attachment)
attachment.url
ty
elif attachment.filename.split(".")[1] == ["jpg", "jpeg", "png"]:
would this work?
you'd replace the == with in
been time since I coded lol
tyy
also is there a get method for message?
I could use bot
nvm
could this work
how do I check if a message includes a user mention?
for what event
@bot.event
async def on_message(message):
gif_channel = bot.get_channel(928014494142197820)
icon_channel = bot.get_channel(928014556926738433)
for attachment in message.attachments:
if attachment.filename.split(".")[1] == "gif":
gif_embed = Embed(title="random gif", color=0x0f0f0f)
gif_embed.set_image(url=attachment.url)
await message.gif_channel.send(embed=gif_embed)
elif attachment.filename.split(".")[1] in ["jpg", "jpeg", "png"]:
icon_embed = Embed(title="random icon", color=0x0f0f0f)
icon_embed.set_image(url=attachment.url)
await message.icon_channel.send(embed=icon_embed)
works or nah
hm, should work
dude I literally said
if a message includes a user mention
you can use message.mentions
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
await bot.process_commands(message)?
how do I check if it's a user mention tho
or is it just of members
you could iterate thru the list and check each member's .bot property
AttributeError: 'Message' object has no attribute 'gif_channel'
I forgot how to send messages to specific channels
I have the ids
can I have an example?
channel = discord.utils.get(ctx.guild.channels, id=msg_id)
await channel.send()
for mention in message.mentions:
if not mention.bot:
# do smth
gif_channel = discord.utils.get(message.guild.channels, id=928014494142197820)
icon_channel = discord.utils.get(message.guild.channels, id=928014556926738433)
alr ty
you're doing message.gif_channel somewhere
When is on_command_error from pysnake executed?
I mean, is it executed when the command the user sent doesn't exist?
What's pysnake ( another fork?)
it fired whenever any error in command occurs in discord.py
including checks , convert failures etc
that too
pysnake is actually a snake game
!pypi pysnake
Lol, yeah, I meant disnake
you mostly see commands.Bot since we import it as from discord.ext import commands
Hello everyone, I have tried to make a bot from python, but I am facing a issue. Please anyone can look into this.
This ^ is the issue which I have faced, I have tried to resolved it but not do it.
are you sure you have a token in the .env file?
Yeah I am sure
verify this by printing it, don't show us ofc
it will print None if the token doesn't exist..
that's your case
you have discord.py installed too?
In pycord , it's discord.Bot
Wait I'll show you, then I regenerate this.
That's not how u use env files in replit , go the lock icon
Try using pycord.Bot instead of discord.Bot
you didn't do what I asked
@slate swan
am I the only one who wants someone to spend 45 minutes trying to hack this guys bot token just to realise its in 0 servers x.x
the token is invalid, we're not dumb
it still has few characters missing lawl
Sorry I didn't get it.
well, what did I ask?
After that?
you dont need to use a .env file if youre using replit
I don't use replit, it stinks, you can ask others
Okay thanks
why are you using a .env tho? don't tell me you're following a YT tutorial pls
Yeah I followed 😅
don't, use the docs instead
Okay
plenty of examples etc
Don't you see a key and value field there?
enter token as key , and the token in value
Yeah there's
Done
use this at the end of the code
bot.run(os.getenv('token'))
under the lock tab on the side enter your bot token as token
any1 know how to make buttons using discord.py?
Still shows error
you dont need load.env at the end either
ok so thats a no...
but... it is kinda cool
Sorry, but still not working
what is it showing you
- make sure the case of the name token in the secrets is the same at the end of the code
- you dont need dotenv
and delete the .env file as well. not needed
using disnake, how can i get more information about failed slash command? This interaction failed <-- all i get
i cant read it. its so blurry
all command error get through CommandError object
Wait
!d disnake.ext.commands.CommandError
exception disnake.ext.commands.CommandError(message=None, *args)```
The base exception type for all command related errors.
This inherits from [`disnake.DiscordException`](https://docs.disnake.dev/en/latest/api.html#disnake.DiscordException "disnake.DiscordException").
This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from [`Bot`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot "disnake.ext.commands.Bot"), [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error").
open up the 🔒 tab on the left. make sure it is spelled "token" all lower case.
delete client.run line.
change case from "TOKEN" to "token"
and add the token inside it the lock tab
if you look here it tells you what line is causing the problem
my_secret = os.environ['token']
bot.run(my_secret)```
i said the wrong one its keep client.run(os.getenv('token'))
does any1 know how to make button interactions using discord.py?
You can see an example on using buttons here: https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
i get nothing there only when i get command wrong, nothing about see whats wrong with slashcommand
oh found it
disnake.ext.commands.on_slash_command_error(inter, error)
None, you can directly use discord.py 2.0
$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[voice]
It shows error
async def on_reaction_add(self,reaction, user):```
with this, how can i get the guild id?
Well, it also shows error
@commands.slash_command(description="Show others that you are Away-From-Keyboard.")
async def AFK(inter):
await inter.response.send_message("Test", delete_after=20)
Why this not work... all i get is "This interactionfailed."
@commands.slash_command(description="Get an invite link to share!")
async def invite(inter):
try:
invite = await inter.channel.create_invite(max_uses=0,unique=False)
except disnake.errors.NotFound:
print("NO INVITE THER!")
await inter.response.send_message(invite, delete_after=20)
But this one does... ?
well yes, but can you see ctx defined?
idk much about disnake but i might be that slash commands take around 2 hours to register, so for development purposes you need to pass in the guild_id of your testing server
see the docs for more info
just write pass_context=true
did you install whatever package you're using after uninstalling discord.py?
well you gotta install your package first lol
do you know basic python?
you should learn basic python before moving to intermediate libraries like discord.py or its forks
hmmmmm somethings wrong
oh wait its replit
role = get(user.guild.roles, id=pr[str(user.guild.id)])```
it is a valid role id, and a valid user in the server but is throwing - discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
I dont know why this is
role = get(user.guild.roles, id=pr[str(user.guild.id)])
print(role)
await user.add_roles(user,role)```
bruh
does any1 know how to make button interactions using discord.py? if yes pls ping me i need help doing interactions
I already answered you @lapis breach ^
ohh... sorry i was busy
No problem ^^
wait didnt you use components for the buttons?
The example shows how to use buttons.
It gives 2 buttons for confirmation, so a "Yes" and a "No" button.
i used components for it didnt even know you could do it this way
also were do you actually send the buttons?
Here:
It creates a view with the different buttons, and sends them with the message.
only discord.py 2.0
how? i think i only have 1.0
you need a discord.Member object
why do you still have dotenv at the top?
you mean like ctx.author?
do you know what that returns?
hey can any body say that how to make a event that bans user on member role update with admin or harm full permissions
the command author
yes but what type of object is it?
discord.Member ig
then yes
I remove it, still shows same error
how do i get 2.0?
what is ur prob
post the whole code here
!d discord.Member.add_roles only takes 1 positional argument by the way
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
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, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
you mean me?
no
what do u guyz need
alais
@boreal ravine ....
still not working
@dim oriolebro
yea
do ```
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py
whats answer.text?
or use poetry
it sends a get request to a webserver which returns a role id so its 914610998009282591
they probably dont know what poetry is
@dim oriolewhat do u need kid
any errors?
no
is answer a message object?
bruh dont ignore ,me
i'm not
Okay
because if you need the content, then you need to do answer.content
token is None I guess but they key exists
Post your code
let me test
@dim oriolewhat do u need anything i can provide u the whole code
!d discord.Message.content
The actual contents of the message.
no
This returns the content of the message as a string
what?
cast it then? Guild.get_role needs an integer
Please don't spoonfeed code
ohk btw just helping him
worked
if anybody could help me pls reply
i thought it needed a string
Nah it needs an int
yes
thanks ;D
What's your name first
venom dc name cant reveal real one
venom dc
ok i am comming waitlemme dinner
What's
dc = discord
didnt work
The concern you're facing
whats the error?
You didn't provide .git
wait i am supposed to download the thing before installing or do i just put the link there?
disnake slashcommand, ok how can i grab created_at it does exists in ctx.message but how about slashcommands in disnake?
Alright
oh my bad
inter, has no message attribute
what
@boreal ravinectx.message.created_at but how i get that datetime when use slashcommands aka datetime of execution of slashcommand?
Yes it would
What are you using to create slash commands
didnt work
disnake
Install git
pip install git?
`import discord
import os
client=discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('token'))`
Then it would be
inter.application_command.created_at
For example
what's the issue
i have downloaded it now what?
Command raised an exception: AttributeError: 'InvokableSlashCommand' object has no attribute 'created_at'
It shows error at the last line i.e. line 20
@bot.slash_command(name="test", description="...")
async def test_command(inter: disnake.ApplicationCommandInteraction):
created_at = inter.application_command.created_at # returns a datetime object
... # your code here, to do whatever with the date
This should work
Try it and see
Do you want when the command was created or when it was invoked
now u can download pip install -U git+https://github.com/Rapptz/discord.py.git
when it was invoked @untold token
Ah I see
how can i remove all roles of an user like
for role in user:
await user.remove_roles(role)```
did u define token properly
didnt work
same error
is git installed in correct PATH?
Yeah
The link that they gave, install git in the path and then run the command
probably not...
user.roles returns all the role objects in a list
then do it
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
how can i just remove all roles of an user
can u send the complete error
what path am i supposed to put it on??
Yeah sure
Because you are not getting the roles
Any error?
Yea unknown role
The bot token isn't correct
Show your entire traceback
your bot's directory
ok
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
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, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Hm
Yeah those are the role objects, so that's working
Try removing a role through its ID
how to make a event that bans user on member role update with admin or harm full permissions
so with
See that if the method is working or not
Any role object
this?
role = ctx.guild.get_role(role.id)```
like this and then do the ctx.author.remove...
still error
bro if anybody is free pls respond
role = ctx.guild.get_role("ID of the role directly")
await ctx.author.remove_roles(role)
The role ID should be an integer
what should i do then?
didnt work
@dim oriole
you don't have to move it
what is the topic of discussion
int
what do i do then?
You can use on_member_update for that
Check if the member has administrator perms and then do whatever you want
still unknown role
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
Still?
no
i kow btw what to do next?
@client.event
async def on_member_update(oldMember,newMember):
is this starting line correct or i should use before,after
this worked
I don't understand, what should I do then?
Oh that worked?
yea
install the git in the path of he directory
Thing
wait
@dim oriole use a try except exception handler to check what role that is raising that error
So like
pip install git?
use dotenv
no it is not like that
for role in ctx.author.roles:
try:
await ctx.author.remove_roles(role)
except commands.errors.NotFound:
... # something here
Already did, still shows same error
ye... im kinda dumb... explain pls
If there is an error while removing the role it will not stop and continue skipping that role
Nope
the error was it tried to take the (@)everyone role from me which isnt possible
@untold tokencan u tell me what is his question? what he wants help about
are you sure you defined your token right in .env?
🔥 Enrol for FREE DevOps Course & Get your Completion Certificate: https://www.simplilearn.com/learn-git-basics-skillup?utm_campaign=Git&utm_medium=DescriptionFirstFold&utm_source=youtube
This Git installation video will take you through the step by step process involved in Git installation on Windows. Git is a distributed version control tool wh...
@lapis breach watch this
^^
Ah see
Yeah I am damn sure
That was the issue
can u send an ss of .env file with your token hidden ofc
i just put that exact code into replit and it works for me
But in mine it shows error, I don't know why?
Well at first you need to check if they have the required permissions or not
!d discord.Member.guild_permissions
property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
Then you need to check if they got any role or not using that event
Sorry, I do know what is it, I am the dumbest person
Btw this is very old
click the lock
and not the proper way to make a discord bot
@slate swanyou can add py from dotenv import load_dotenv load_dotenv()
They are called secrets
I did it already it gives error
ik that. im dumbing it down
seems like you have an issue with .env file
Done
os.getenv('token')
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all()) # This is subclassed version of discord.Client(), but it has more features and comes with a message command framework built in, the framework allows us to create commands in a much more better and easier way than raw on_message events.
@bot.listen() # This decorator creates and adds an asynchronous event listener to the bot, with the type of the event to listen to
async def on_ready():
"""Called when the client is done preparing the data received from Discord."""
print("Bot is ready")
@bot.command() # This decorator creates and registers the command that you created, using the commands framework.
async def test(ctx: commands.Context):
# takes context object as the first argument, Context object is special object that is passed by the commands framework that contains necessary data, like command invoker, the gold and channel where the command was invoked and more
"""A test command"""
await ctx.send("test")
@bot.listen()
async def on_message(message: discord.Message):
"""Called when a Message is created and sent."""
if message.author.bot:
return
... # your code here
bot.run(token)
A simple example on how to create a bot using the commands framework
this is the correct code for py
You can't have env files on replit
That's the issue
key = the word "token"
value = your bot token
You need to use secrets and then get your data from that
ohh not familiar with replit tbh
i knwo first go to sscrets make a variable token and add import os and token = os.getenv('token')
easy
for replit



