#discord-bots
1 messages Β· Page 886 of 1
so, first you make a command manually with a decorator
100 servers*
75
Ok @client.commands()
command
@slate swan can you dm me?
This slowmode sucks
no, I dont do dms, hunter does
you can request for the verification on 75 itself and maybe if you're unlucky you may not get the message intents π€‘
But yeah, 100
Ok
Max server limit for unverified bots are 100, that's why I said that, but okay
Brb
Lemme get my token and make a repl
Stay here
type in 1 line and the slowmode won't suvk
is that an order or what
Where to stay? π
Let's ping a mod to reduce the slowmo
@blissful lagoon can u please reduce the slowmo duration of the channel?
Got the token now lemme do the importing and stuff
Cool
can anyone tell me how to access my bot instance in a Modal?
I have a button that sends the modal

really though, 6s is a lot π
I haven't used disnake modals, but dont they have an interaction arg?

yeah
you can pass in the bot object as a argument in the init and make it an attribute of the Modal
Can't really do anything since pinging the mod role for such a small thing would be an overkill
!d disnake.Interaction.author exists then
The user or member that sent the interaction.
they have disnake.ModalInteraction
Oh, hmm
so this would be the bot?
!d disnake.ModalInteraction.user
property user```
The user or member that sent the interaction. There is an alias for this named [`author`](https://docs.disnake.dev/en/latest/api.html#disnake.ModalInteraction.author "disnake.ModalInteraction.author").
Ouh, that was a wild guess
But u shouldn't ping individuals either 
what does this mean by "sent"
am i the only one whos never even seen a modal
Clicked the button
I cant paste my token aaaa
I will need to manually send it
us.
that's not what i want i want the bot instance
def require(package): return __import__(package)
discord = require("discord")
π Idc if it works or not, but it does look uwu
then, for me view, i need to do it again?
We don't have any other choice
!d disnake.ModalInteraction.bot actually
property bot```
The bot handling the interaction.
Only applicable when used with [`Bot`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot "disnake.ext.commands.Bot"). This is an alias for [`client`](https://docs.disnake.dev/en/latest/api.html#disnake.ModalInteraction.client "disnake.ModalInteraction.client").
@novel apex?
ok
Uhhh, I better not comment anything lol
Indeed. It will work but won't provide u typehints
Idk but i use
import discord
from discord.ext import commands
client = commands.Client(command_prefix("your prefix"))
!e
def require(p):
import p
require(random)
@maiden fable :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'random' is not defined

nobody cares 
time to jsify py π
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.

!pip javascript

!pypi justuse
π

yes
hello guys, my code in sublime text looks like this, how can i do reconvert to the normal looks cause my bot commands don't work

ctrl z
don"t work
well
@slate swan I am ready,what now?
I imported discord and did the setup and stuff
your fucked, fix it manually
@boreal ravine alr thanks mate
ask @maiden fable he's too much of a pro π
That's a lot of conditionals ig 
or maybe they indented commands inside commands
@maiden fable ...
why use that though, normal imports work just fine
It's really useful when you need to avoid circular imports
you're*
ohisee
He isnt here @slate swan comon help me
Typo.
What happened
look like discord.py is alive again https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
no
@tight obsidian please reduce the slowmo π₯Ί
we know
your late by 12 hours
what?

Hunter back
I have to study, so gtg, @maiden fable help as you said you will 
you're*
You are late π
Typo.
no
π€£
Why does sqlite3 on git reset the variable value after restarting the bot, but everything works in sublime, why?
Eh, I came back for only a min anyways
jesus fucking christ
@cold sonnet mind helping @drowsy thunder?
Any help
git? Are you using something like heroku
y'all are passing him to each other like a ball
@slate swan gonna help u
I laughed so hard on this 
I myself am helpless, btw who u?
Bro, I have to go rn urgently, but dont wanna leave him like this here
Smh anyways
Yes
@slate swan are you sure about that?
@drowsy thunder what's your problem though?
@drowsy thunder do u know about events?
okay @drowsy thunder tell your problem

Lol


Cyaaa
Heroku doesn't supports Saving files so it will always get reset
bai bai, cyoutoo
good night
@bot.listen('on_message')
async def on_message(message):
if message.author == bot.user:
return
if isinstance(message.channel, discord.DMChannel):
guild = bot.get_guild(875771903799877683)
channel = guild.get_channel(876553804861034496)
await channel.send(f"> {message.author.mention} m'a mp en disant : {message.content}")
return
``` hello, i have this error, how can i fix this please ?
This video has the bot and I wanna make it in
https://youtu.be/APY66hYarAc
In this video I made 500+ people perform a reaction speed test in Discord, where the first place of each round would receive a prize of Discord Nitro accompanied by a special role in my server!
Thanks for watching the video!
------------LINKS BELOW------------
β© JOIN MY DISCORD SERVER β©
https://discord.gg/Sound
β© WATCH ANOTHER VIDEO β©
https...
why indented return
And what to do? can it be fixed?
Yea yea good evening lol
You sure that you saved the code before running it
don't know its work before so idk
yes
Gn π
Who will help?
Whoever wants to,tell how long there coding on python
I will choose the most experienced one
It cannot be fixed till the time you're using heroku
hah can't be me
thats pretty easy
I'm not gonna watch the video mate
Just tell me what you want the bot to do
Then put code here lol
I wanna count how long in ms
See who was the first person who reacted to the command message
bot edits a message then waits for the first few people to react to the message
Actually, just use bot.wait_for, I just remembered
i should not indented it ?
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
So a / command sends a message sees who reacted first and sends exactly how many ms after.
no, you shouldn't indent it
you only indent stuff in statements
I want to code a bot like a casino, where can i start?
You know python?
i have the same error
class casino:
i haven't the error but when i changed my editor (sublime text -> pycharm) this error appears@cold sonnet so maybe its this ?
help = "Nobody seems to help me"
print(help)
it has to be an IDE problem, I don't see a syntax error
yeah, but almost nothing about coding in python
Then learn python first
pls learn python before doing a bot
oh I meant coding bots mb
Check the pins by Sebastian π
help is a builtin
It will be hard if you dont learn python first and not what I would recommend
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
@manic wing re: your issue, you can implement button cooldowns yourself
shadowing help() no good
I KNOW python
- Send the message and save it in a variable (
variable_you_stored) - Use
bot.wait_for("reaction_add")with a check which makes sure that the message on which reaction was added was the same message (reaction.message== variable_you_stored) - Use datetime.datetime.now() to get the current datetime
- Subtract that datetime from
variable_you_stored.created_at
my head hurts from coding today so I messed up
for using anything I wrote, you need to learn python.
Ok
I mean Python Coding Language
I want to code a bot like a casino, where can i start? I know python but nothing about coding bots and clients
Watch the video dude
I think its much complex than this
Start with simple commands to understand how the api wrapper works π
im not saying i cant, but it would be much easier for the less experienced if there was a cooldown deco
No it's not , that's all you need to do
import discord
bot = discord.Client(loop=None)
@bot.event
async def on_socket_raw_receive(data):
...
bot.run(TOKEN)
``` `TOKEN` is not defined?
with a for loop for how many times you want the reaction to be got
TOKEN = 'your token'
If you don't have time to explain us about the vid we don't have time to give u detailed answers 
is there like a guide or smth I can follow?
thanks!
π³
what's the loop kwarg for
!d disnake read the docs and check the repo for some examples
No documentation found for the requested symbol.
i don't exactly know
It's the current ayncio loop being used iirc
xd
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
What 

so it's optional
yes
Yea its an asyncio.AbstractEventLoop
does the lib pass something to it after?
yes
it has to
if it's None, library creates a new loop
discord/client.py line 235
self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() if loop is None else loop```
I'd just loop or asyncio.AbstractEventLoop
Oh ok
First do pip install discord.py
Then in bot.py
import discord
from discord.ext import commands
client = commands.Client(command_prefix("your prefix"))
token = "your token"
@client.command()
async def hello(ctx):
ctx.channel.reply("Hello, World!")
bot.run(token)
...
This is the basic hello world command
no, that's not how you define a function
A colon can change Everything
this is wrong in hundreds of ways

ummm nice
a) call it bot
b) its commands.Bot
c) its command_prefix= because its a kwarg
d) you need to indent the reply
e) you need to await the reply
f) you cant reply to a channel, only to a message or ctx
g) its client at the top but bot at the bottom ?
Yeah π€£
import discord as dc
client = dc.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('your token here')
I found this tho idk what half of it does
import discord as dc??
Nah
yeah
Lol
it seems so unnatural yet so right
pls fix or delete this, its spreading misinformation and most certainly will confuse people
I got no idea why we need any of this :/
how would i make it so a command could be either none or true it would be like
$create dm 1
that would do something different compared to $create dm
use commands though
You will learn 
This is the thing we wont use
I hope so
whats that
it's a thing of commands.Bot
@harsh stump dm me if any help needed
You are not helping him from the moment they are here 
him
true
they
im he/him
Peter, you are confusing yourself.
Lol sorry
Ok 
no, rather type him than them
aight back to making a discord bot
@client.event what does this do?
or should I just go and learn?
it tells the lib that the function defined is an event
^
once4thewin do you have any recent experience with python?
yup
It defines an event
event listener
I just didnt get into oop
Huh
!d discord.Client.event
@event```
A decorator that registers an event to listen to.
You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events).
The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)"), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.9)") is raised.
Example
```py
@client.event
async def on_ready():
print('Ready!')
great, so you're aware of basic things like python syntax, Data types, classes/OOP and asyncio right?
everything accept classes/oop
decorators are not an OOP concept
should add decorators to the list
^
A decorator takes in a function, adds some functionality and returns it. In this tutorial, you will learn how you can create a decorator and why you should use it.
thanks
I am a bit confused of the cogs thingy
def should know OOP for dpy
and asyncio can be confusing so I would put some effort into that
cool then, you may learn OOP alongside Making the bot π€
pogg

okayy
meh!
enjoying the chat :/
Caeden said u a dude
!ot π³
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
lmaoo
explicit feelings
........?
.
smh
wasnt me π³
whatever
π³
#help-pretzel
Help meeee
is it related to discord bots?
Yeah
How can I check if a whole Embed message has a specific word in it? Does it work with message.content?
embed message?
My bot is not assigning the roles can someone help
no
!d discord.Message.embeds
A list of embeds the message has.
async def on_reaction_add(interaction):
message = interaction.message
button_id = interaction.component.id
if reaction.emoji == ":white_check_mark:":
member = message.guild.get_member(interaction.user.id)
role = message.guild.get_role()
await member.add_roles(role)
response = await interaction.respond(embed=nextcord.Embed(title="Verified"))
@bot.command()
@commands.has_permissions(administrator=True) # you need to import command from discord.ext if you want to use this -> from discord.ext import commands
async def verify(ctx):
embed = nextcord.Embed(title="VerificaΓ§Γ£o",
description="Clica para te verificares",
colour=Color.orange()
)
embed.set_author(name="Nome", icon_url="")
embed.add_field(name="Campo 1", value="Not an inline field!", inline=False)
embed.add_field(name="Campo 2", value="An inline field!", inline=True)
embed.add_field(name="Campo 3", value="Look I'm inline with field 2!", inline=True)
embed.set_footer(text="Footer")
embed.set_thumbnail(url="")
emoji = ":white_check_mark:"
message = await ctx.send(embed=embed)
await message.add_reaction(emoji=emoji)```
is it in a command or on_message?
you're gonna take this list
I think I have to loop through the whole embed title, description and fields, right?
My bot is not assigning the roles can someone help
ππΏ
Send code
...
.
ok ty
!code π
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@bot.command()
async def on_reaction_add(interaction):
message = interaction.message
button_id = interaction.component.id
if reaction.emoji == ":white_check_mark:":
member = message.guild.get_member(interaction.user.id)
role = message.guild.get_role()
await member.add_roles(role)
response = await interaction.respond(embed=nextcord.Embed(title="Verified"))
@bot.command()
@commands.has_permissions(administrator=True)
async def verify(ctx):
embed = nextcord.Embed(title="VerificaΓ§Γ£o",
description="Clica para te verificares",
colour=Color.orange()
)
embed.set_author(name="Nome", icon_url="")
embed.add_field(name="Campo 1", value="Not an inline field!", inline=False)
embed.add_field(name="Campo 2", value="An inline field!", inline=True)
embed.add_field(name="Campo 3", value="Look I'm inline with field 2!", inline=True)
embed.set_footer(text="Footer")
embed.set_thumbnail(url="")
emoji = ":white_check_mark:"
message = await ctx.send(embed=embed)
await message.add_reaction(emoji=emoji)
on_reaction_add takes an interaction??
!d discord.Embed.description / related attribute where the word can be present
The description of the embed. This can be set during initialisation.
U cannot use a event as a command 
if len(ctx.message.embeds) == 1:
embed_content = ctx.message.embeds[0].description
# embed_content is the description of the embed```
What's wrong with that?
....uh
okay okay ty, also how many fields can a embed have max?
why tf not just member = interaction.user
nvm me
same question
so I need to put
@bot.event
okay ty
what a save
Because it's interaction.user
By any other name just as sweet.
they get the Member object by get_member
||nextcord's stupidity||
lmao
and they don't have user as an argument
(quietly uses on_raw_reaction_add)
much better tho
so I put "reaction"?
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.
take these arguments
AttributeError: module 'discord' has no attribute 'Client'
Whats wrong here?
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
show code
meanwhile hikari with 10+ reaction related events hmmm
import discord as d
client = d.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(TOKEN)
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
huh?
happy freecodecamp noises
The bot continues without giving the role
try running this in your cmd line py -m pip install discord --upgrade
nah, codingwithswatick (idk i forgot how to speel)
I did
use commands.Bot
*... pip install -U/--upgrade discord
.
linux or windows?
windows
Any Os
relax π³
events as commands 
The bot continues without giving the role
send updated code
context plz?
im on 11% battery life
so what do I do?
I had some respect for freecodecamp
But bruv
Replit
and bad tutorial overall
@bot.command()
async def on_reaction_add(interaction):
message = interaction.message
button_id = interaction.component.id
if reaction.emoji == ":white_check_mark:":
member = message.guild.get_member(interaction.user.id)
role = message.guild.get_role()
await member.add_roles(role)
response = await interaction.respond(embed=nextcord.Embed(title="Verified"))
@bot.command()
@commands.has_permissions(administrator=True)
async def verify(ctx):
embed = nextcord.Embed(title="VerificaΓ§Γ£o",
description="Clica para te verificares",
colour=Color.orange()
)
embed.set_author(name="Nome", icon_url="")
embed.add_field(name="Campo 1", value="Not an inline field!", inline=False)
embed.add_field(name="Campo 2", value="An inline field!", inline=True)
embed.add_field(name="Campo 3", value="Look I'm inline with field 2!", inline=True)
embed.set_footer(text="Footer")
embed.set_thumbnail(url="")
emoji = ":white_check_mark:"
message = await ctx.send(embed=embed)
await message.add_reaction(emoji=emoji)
This is my code, it doesnt assign the roles
it would also be if reaction.emoji == "β
":
str(reaction.emoji)
dude, you didn't get any roles to add in the first place
In my code I have it
the role id?
member = user when you have the right arguments, and there's not even a need to do that
so just user.add_roles(role)
can I get a discord bot tutorial?????
and btw how is on_reaction_add passing an interaction?
check pins
I changed to reaction


nextcord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.on_message_edit "nextcord.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://nextcord.readthedocs.io/en/latest/api.html#nextcord.on_raw_reaction_add "nextcord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Message "nextcord.Message") being reacted, access it via [`Reaction.message`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Reaction.message "nextcord.Reaction.message").
This requires [`Intents.reactions`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Intents.reactions "nextcord.Intents.reactions") to be enabled.
Note
This doesnβt require [`Intents.members`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Intents.members "nextcord.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://nextcord.readthedocs.io/en/latest/api.html#nextcord.on_raw_reaction_add "nextcord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
ok
I will try it

there'a a lot yet to replace
im crying can someone please help me
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.
There there there, can I sing u a song

do I use nextcode then?
U could use disnake
The discord.py library has now been discontinued by its maintainer.
nextcord isn't any better than any other lib
it's back
π€£
It didnt work

.
now you have user as an argument?
then you could start with replacing member in member.add_roles()
or maybe using the better_on_reaction_add
called on_raw_reaction_add
which takes a payload arg
and throws the whole thing we just did away
command to mention channel ?
!d discord.TextChannel.mention
property mention: str```
The string that allows you to mention the channel.
tq
(ctx: commands.Context) WHat does this mean?
typehinting ctx
tells your IDE that ctx is a commands.Context instance
so it can recommend you attributes while typing
How to fix this error?
WARNING: You are using pip version 21.2.4; however, version 22.0.3 is available. You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
this is not an error, its a warning ;-;
and this is the wrong channel
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
ok srry
what
@harsh stump
doesnt help
do you know what instances are..?
you know when you write down ctx and then a .
if you don't typehint, the IDE doesn't recommend anything after the .
if you do, the IDE can recommend you stuff to write after the .
(IDE = text editor with extra stuff)
(. = .)
idk, I do have to currently
I delete them after anyways
(IDE = code editor with extra stuff, an Integrated Development Environment)
nerdy
other people can ban eachother, how do i make it so they cant?
to set type checking to strict in vsc in setting.json you can use "python.analysis.typeCheckingMode": "strict",
how.
thats likely the fastest way to change it
the warning literally tells you how to fix it
can you tell me a example using this command
if my channel name is lets say welcome_channel (which is defined)
@cold sonnet
They already shouldn't be able to do so, but anyway, you can decorate the command with @commands.has_permissions(ban_members=True) or something
@bot.command()
async def channel(ctx, channel_id):
await ctx.send(bot.get_channel(channel_id).mention)
look no perms
ok tysm
Guys, the question is off topic, but do you know the hostings are free (it would be desirable, with git binding)
where do i put that? under the async def?
Below the decorator of the command, I think. Maybe it doesn't even matter. I am not sure.
You can, but also depending on the converter it will also do an API call when not in cache
ty
If it needs to be a text channel in a server, you can annotate it with discord.TextChannel
async def hello_world(ctx: commands.Context):
await ctx.send("Hello, world!")
``` Does ctx mean anything or can it be like``` lmao: commands.Context```?
or if i have to use in embeds
Note: I think the library raises an exception if it failed to convert
just do the same in the description
The latter
ok
But it is short for "context"
!d inspect module iirc
Source code: Lib/inspect.py
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.
There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
Using the inspect module they look at the callbacks signature ^
!d inspect.signature
inspect.signature(callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)```
Return a [`Signature`](https://docs.python.org/3/library/inspect.html#inspect.Signature "inspect.Signature") object for the given `callable`...
Wym
The call the callback with the dispatched args but also command and interaction have it called hard-coded
default args?
how does context get passed to the function
E.g ```py
@bot.event
async def on_message(message: discord.Message) -> None:
...
bot.dispatch("message", discord.Message(...))
``` calls on_message(discord.Message)
andy, do I have the permission?
And for commands it's the same way, but just hard-coded for context
Same with interaction callbacks
Actually I messed up my wording, no it's not the same way kek
They directly call the callback function with the interaction/context
They also get the other args via converters

@slate swan :white_check_mark: Your eval job has completed with return code 0.
OrderedDict([('default', <Parameter "default">), ('arg1', <Parameter "arg1: str">), ('arg2', <Parameter "arg2: int">)])
Anyone know how to make anti spam bot?
I tried to learn decorators, but well, I don't wanna share my experience π
how do I get my bot instance from modals? inter.bot doesn't seem to workpy channel = inter.bot.get_channel(898198212022779935) AttributeError: 'Suggestion_Modal' object has no attribute 'bot
no
mind showing the whole modal code?
it's a modal
def wrapper takes func
....?
def decorator takes the args and kwargs
Oh wait, nvm I forgot idk how decos work
I agree
or maybe you're just too bad it
did you include self as the first argument in the callback
async def callback(self, inter: disnake.ModalInteraction) -> None:
embed = disnake.Embed(title=f"A new suggestion has been submitted.", color=disnake.Color.blurple())
embed.set_author(name=f'{str(inter.author)} has submitted a suggestion', icon_url=inter.author.avatar.url)
for key, value in inter.text_values.items():
embed.add_field(name=key.capitalize(), value=value, inline=False)
embed.set_footer(text=f"Suggestion by {inter.author.name} | {inter.author.id} {datetime.datetime.utcnow().strftime('%A at %H:%M')}")
channel = inter.bot.get_channel(898198212022779935)
upvote_emote = inter.bot.get_emoji(898204326483349564)
downvote_emote = inter.bot.get_emoji(898204314449874984)
success_embed = disnake.Embed(description='Your suggestion has been submitted!', color=disnake.Color.green())
await inter.response.send_message(embed=success_embed, ephemeral=True)
message = await channel.send(embed=embed)
await message.add_reaction(upvote_emote)
await message.add_reaction(downvote_emote)
I am just bad at it lol ik
Anyone know how to make anti spam bot?
I can relate 
BTW oki is still waiting π
||for?
||
await waits for a user to call this function?
Didn't check yr DMs?
nope, no dm
Lmaoo
Anyone know how to make anti spam bot?
?
@formal basin
idk on which ID he DMed you, just check both of yr IDs
yeah doing
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
whats wrong here?
Do I put that into an event
And if he hasn't sent u already, he is getting killed by me
still nothing, im curious now, explain it to me in dms plees
It is a Bot subclass
Better would be if he himself tells u (:
idk, how do I do it?
i wanna make a stop spam cmd but i have no idea how to , like in the middle of spamming, when i give a cmd the spam shud stop
hurts my feelings, but alright
!custom-cooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
Lmao ok stop hurting yr feels, I'mma tell u
!e ```py
import inspect
def decorator(default, arg1, arg2):
print(default, arg1, arg2)
def wrapper(func):
print(func)
return func
return wrapper
#to make the not decorator callable you wouldnt return wrapper here
eg the difference between bot.listen() and bot.event
@decorator('hi', 1, 2)
def myfunc():
pass```
@manic wing :white_check_mark: Your eval job has completed with return code 0.
001 | hi 1 2
002 | <function myfunc at 0x7fb8d186b370>
Utilise this
tysm
(dms π)
is this what you mean? you pass func into the wrapper
huh?
just lock the channel?
reptile i am working on the fun cmds but i hav exams now
stop messing with my brain please π
well first you would remove the def wrapper because you'e not calling the decorator hence you dont need it
i want others to chat tho
no, it would be like ```py
def decorator(func):
print(inspect.signature(func).parameters)
you dont need the inner function
but anyway
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) I keep getting this error, how do i fix it?
u didn't return func
thats cus you're not returning func
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
003 | world
see
ill go print dir on func and let you know
did you just say python was unpythonic
discord/client.py line 1077
def event(self, coro: Coro) -> Coro:```
What is even happening here lol
can someone please help
when you dont call the decorator you dont need an inner func
reinstall dpy
reptile make a help channel and we can talk there, we're spammign discord-bots
have you installed discord?
yes
reinstall it and try then
why did I read it as replit
lmao same
Was gonna link u to the replit discord server π
doesnt work
import discord
import random as r
from discord.ext import commands
uh
return Complex(((self.a * self.b) - (obj.a - obj.b)) + ((self.b*obj.b)+(self.b*obj.a)))
TypeError: Complex.__init__() missing 1 required positional argument: 'b'```
why would i get this error even though I have mentioned a and b alongside self in __init__ ?
are you using pycord?
whats that
this reaction tho lmaoo
It wonβt do anything
It runs but it doesnβt send anything in when I spam
@cerulean olive bro u from the future or what
I really need help, what is happening
Yes
Nah I just need a simple bot template I am lazy 2 do all the shitty little setting up
I mean, 8.9 doesn't exist lol
youre here too lmao
Oh yeah
sus
3.8.9
how do i save cooldowns in a file
so that they dont reset everytime i restart the bot
i tried searching online
and found this
cooldown_info_path = "./cooler.pkl"
class Bot(commands.Bot):
async def start(self, *args, **kwargs):
if os.path.exists(cooldown_info_path):
with open(cooldown_info_path, 'rb') as f:
d = pickle.load(f)
for name, func in self.commands.items():
if name in d:
self.commands[name]._buckets = d[name]
return await super().start(*args, **kwargs)
async def logout(self):
with open(cooldown_info_path, 'wb') as f:
pickle.dump({name: func._buckets for name, func in self.commands.items()}, f)
return await super().logout()
pickle.dump({name: func._buckets for name, func in self.commands.items()}, f)
AttributeError: 'set' object has no attribute 'items'
it gives out this error. not sure if you can save cooldowns lol
you know you can just save them in a db
self.commands is a list of commands.Command objects
but how do i access them
When I spam nothing happens
how do i access the cooldowns to save them somewhere
!d discord.ext.commands.Command.get_cooldown_retry_after this?
get_cooldown_retry_after(ctx)```
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
and does this give a list or something of the cooldown bucket
this returns the seconds after which the cooldown will expire
like when i restart the bot, all the cooldowns just go away
!d discord.ext.commands.Command.is_on_cooldown
is_on_cooldown(ctx)```
Checks whether the command is currently on cooldown.
i need to save the cooldowns for every user from every server so that theyre there when i reload the bot
Use a database
dude first i need to find a way to even access the built in dict/list of all the cooldowns right?
Idk what you're doing
look. when you shutdown the bot and restart it, all the cooldowns go away. i have commands with 5 days of cooldown. so i need to save these cooldowns in a file so that i can reload these cooldowns and they remain the same when i restart my bot
Yeah so use a database
?
lmao
Tell me why a database wouldn't work
And he left
@sweet tiger
He left the server lmao
What the π
I have cog files in a commands directory
I want to retrieve all of those classes' docstrings dynamically without having to specify each file's name. How to do it?
for command in bot.commands: print(command.doc)
classes or commands?
oh misread that but its the same thing
Hahaha
for cog in bot.cogs: print(bot.cogs[cog].doc)
can I add custom attributes to the cog ?
good idea
@manic wing thanks mate
mwah
if I put this in on_ready function, will I not get rate limited?
You won't
you only get ratelimited when making api calls
ah okay then
One message removed from a suspended account.
er
!d disnake.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleβs messages, you need the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
well
if you want your message to be deleted after every command you can make an after_invoke and delete it there
no you didnt implement the correct code
What did I do wrong then
read that embed again and see what you are missing
Ok
Ohhhh
@spring flax hows the hunai rewrite going?
One message removed from a suspended account.
which message do you want to delete?
One message removed from a suspended account.
What happened
One message removed from a suspended account.
?
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
One message removed from a suspended account.
Cool
in the function you sent it clearly shows ctx as an arg
Itβs not moderating
Oh @dry kelp you here π
thats an example code of how you would do that
not just a copy paste and "here im ready to control spams in your server, sir"
you could do any action you want
SELECT * FROM <table> WHERE condition
ssshhhhh ? place holder is for sqlite, not pgsql
ah
then what should it be....
it should get the wait.. omfg cooldown
this is a set prefix command yk
may i know what library are you using? asyncpg?
So what do I do to make it do something
you'll be using $index
???
this example in the docs
lemme send my code in a myst
its their wish, there's no limitation
await spooky.pg_con.fetchrow("SELECT * FROM Prefix WHERE guild_id = $1", ctx.guild.id)
did you learn sql ?
can i ask for help hwre
ask that in discord developers server you will get the answer there
yea thats what the channel is meant for
i havent coded at all in 5 months so i forgot how to fix this issue
you cannot have that character in python
but what character
the red dots
i cant get rid of them
erase it..
i literally cant
refresh your tab
im back
what kind of methods/solutions are you guys hoping would be implemented into discord.py or forks?
in discord.py i think its coming but app commands in cogs without having to manually add them to tree
or use a group like a cog
What happened to my bot?
thats what happens when u use replit
And what should I do now?
Replit for discord bots π
probably best solution is to just wait
Not use replit
even better is to migate to something else
Use a full-fledged editor such as VScode, pycharm, emacs, etc
So this problem can disappear by itself?
repl.it uses a shared IP so whatever IP your repl has is shared with a couple other people, so if someone in that IP gets ratelimited or something, all other people on that IP will also get that ratelimit.
No, it will happen again a lot
If you're using replit nothing you can do about it but wait 10-15 minutes every time it happens, and it will happen a lot
Also wanted to add that if someone else using your IP does something malicious, it's possible for you to get banned as well
Can a VPN help in such a situation?
In this case, nope.
You using a vpn would still send requests from replit's machines
Wouldn't change anything
The easiest and best way would be to not use replit and switch to something better
use kill 1 in shell and ip resets
best solution again is to migrate to a proper VPS, or if you can't do that, migrate to something like Heroku. While Heroku has its own share of problems (one being that it isn't designed for Discord bots), you won't get ratelimited every 10 seconds.
Do I see Robin? π
plus loads of VPN IPs are banned by discord because it turns out people who abuse the platform use VPNs too
That is, in the future, replit will no longer be suitable for creating bots at all, since all replit machines will be overloaded?
any features you guys are looking to be implemented? π©
Replit has never been suitable for creating bots
Not in the future, it's simply not suitable for it.
And they have always been overloaded since the machines are extremely underpowered
They weren't designed to host full fledged apps that are up 24/7, they were only meant to run the one-off small code snippet that you just wanted to check if it works but were too lazy to load up an actual IDE
πββοΈ yea, bot's reading About-Mes
but i dont think discord api would ever allow that
- because you're using a shared IP, 2) because you're using fairly underpowered systems, and 3) because you also have to keep alive the connection since again, it wasn't made for hosting
wont be implemented, too big of a privacy issue
If you want an actual host, look into AWS, google cloud services, or microsoft azure, they're all excellent and are used in the industry a lot
it's only really returned in the client user, as bio
yeahh, would be the same scenario as the message intents
GCP has an always free tier you can use (f1 micros iirc?)
but I'm not sure how it would go privacy-wise anywhere else
Yeah many do, I know for a fact AWS has a free tier but it's not always free, 700 hours/month for 12 months on t2.micro instances
For small discord bots GCP or AWS free tier will more than suffice
Oracle cloud gives you quite a lot always free on ARM archs, but that comes with supporting oracle which is ehhhh
And due to their architecture if your bot starts growing and you need more resources, they make it incredibly easy to scale your app
Okay, we'll have to put up with it and switch to heroku and github
heroku is equally as bad as replit
Heroku isn't much better than replit either
Hey, I am trying to check if someone has pinged a user from a list in a json file. Is this the correct way to do it?
@commands.Cog.listener()
async def on_message(self,message):
with open("nopinglist.json") as f:
data = json.load(f)
no_ping_list = data["no-ping-list"]
if no_ping_list in message.content:
neither are made for always-on apps like discord bots
the 300$ of azure credits from gh edu pack have been working nicely for me
Why not use vscode/pycharm?
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
It's too complicated for me.
(Assuming you're using replit for the IDE and not the "free hosting")
can you not do await message.edit(suppress=True)?
i thought that suppressed the emebds
How so? It's just as easy or easier than using replit/heroku and will save you a lot of headache down the road
!d discord.message.mentions , you can do a list comps to get all the ids of mentioned people
No documentation found for the requested symbol.
!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.
how do you remove the embeds from a message?
edit the message and set embeds=None
no like
await message.edit(embeds=None)
https://github.com/ when you send this link it autoshows the embed
supress will do the thing, but there embed means all the attachments
like https://github.com/?
yes
<link>
when i do await message.edit(suppress=True) it doesnt remove the embed
oh you mean that
no, how do i make the bot suppress another users message
supress_embeds=True
?
!d discord.Message.remove_attachments
No documentation found for the requested symbol.
@tree.context_menu(name='Info', guild=test_guild)
async def info(interaction: discord.Interaction, member: discord.Member):
embed = get_member_info_embed(member)
await interaction.response.send_message(embed=embed, ephemeral=True)
anyone know why this won't work D:
message.edit(embeds = [])
thats not it
But I'm asking how to check if a pinged user is a list from a json file, this is what I have in the json file.
{"no-ping-list":["@true quartz","@true quartz"]}
await message.edit(embeds = [], content = "content")
Using json as a database πΏ
bro, it's just for one small thing that will rarely get updated it really doesn't matter πΏ
Store just the IDs, then on_message, do set(message.mentions) and get the intersection between set(message.mentions) and the set from your json, if the intersection length > 0, ping was in the message and in the json, else, it wasn't
It does matter
why tf is suppress not working
I tried to print Korean language on my bot discord but its printing invalid character someone have an issue ?
depends on your system, not a python limitation
So i can use utf-8 ?
!e print("μ΄λ΄")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
μ΄λ΄
Cant*
see, it works
Is there any documentation on set(message.mentions), I don't really understand how to use it
in your console/terminal right?
Yea
some systems dont support languages until you download them
So how i can make them support
message.mentions is just a list, we're converting a list to a set
!e
myList = [1, 2, 2, 3, 3, 4, 4, 5, 5]
print(set(myList))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{1, 2, 3, 4, 5}
What even is set()
!e
# intersection
x = {1, 2, 3}
y = {2, 3, 4}
print(x.intersection(y))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{2, 3}
!d set
class set([iterable])``````py
class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.
Sets can be created by several means:
β’ Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`
β’ Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`
β’ Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
Yeah I don't understand
use this to figure out if pinged users are in the json
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{1, 2, 3}
removes all duplicates if there are any
Why are the curly braces?
that's the syntax for a set
Oh
[] for list
{} for set
So like this?
mentions = set(message.mentions)
with open("nopinglist.json") as f:
data = json.load(f)
no_ping_list = data["no-ping-list"]
if mentions in no_ping_list:
sets also have special methods like intersection, union, difference
!e
print(type({1, 2}))
@final iron :white_check_mark: Your eval job has completed with return code 0.
<class 'set'>
Cool
You can't check if a set is in a list
Well ok I guess you can but it won't give you what you expect
how do i get a guilds picture?
You need to take the intersection between the set(message.mentions) and no_ping_list
!d discord.Guild.icon
property icon: Optional[discord.asset.Asset]```
Returns the guildβs icon asset, if available.
property url: str```
Returns the underlying URL of the asset.
@quaint epoch
yeah lol i just checked the docs
Sorry what do you mean by intersection, can you send an example?
but thanks
!e
# intersection
x = {1, 2, 3}
y = {2, 3, 4}
print(x.intersection(y))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{2, 3}
intersection returns what 2 sets have in common
In this case both sets had 2 and 3 in common
ah ok
there's also a shorthand for it which is just &, i.e. {1, 2, 3} & {2, 3, 4}
Oh really? Didn't know that π
union is |
In that case, just do set(message.mentions) & set(no_ping_list)
Like this?
mentions = set(message.mentions)
with open("nopinglist.json") as f:
data = json.load(f)
no_ping_list = data["no-ping-list"]
print(mentions.intersection(no_ping_list))
Actually you'd probably want to map it to IDs but my point still stands
it's basically the same as bitwise stuff, {1} ^ {1, 2} == {2}
Oh yeah, Java has the single operands for bitwise, double for boolean operators so that makes sense
well, same kinda concept but on different things
Make sure your nopinglist.json only has the ids, without the <@!> stuff
and you'll also want to parse the string to an integer as it'll probably be a string in the json
Yeah I changed that
Okay, then parse it and set() it to get the set
{"no-ping-list":[950068134503678013,950068134503678013]}
it converts the given obj to a set like int()
Maybe i install korean language to my computuer
yea...
I already have set()?
mentions = set(message.mentions)
Nothing happened..
message.mentions is a list of discord.Member objects, you can't take the intersection of 2 sets containing 2 different objects
set(map(lambda m: m.id, message.mentions))
Ok now how do I more do more if they have mentioned a user in the no-ping-list?
Check for truthy/falsy value of the intersection
truthy value - user in the no ping list was pinged
falsy value - user in the no ping list was not pinged
how do i get a list of all of the actions that have occurred in a guilds audit log?
like, all of the entries?
ratelimits:
oi what fork is the best fork that uses the discord namespace
just use discord.py
it returned
but that one doesnt have buttons
Why the life hate me
yeah it does
it has most if not all of the new features
oh
anyone got any features they want discord.py & forks to implement? π©
How many spaces do I do on line 25
Is there any way, i can make a command in another file without cogs?
8 in total as its indented 2 levels
!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
yeah?
you just do ```py
import discord
from discord.ext import commands
@commands.command()
async def command(ctx: commands.Context):
...
``` and then import that into your main file and do bot.add_command(command)
each level of indentation can be 2 or 4 spaces mostly 4 to follow pep8 or some editors do it by default
so whos changed back over to dpy here?
Thank you
not me
Like this?
set(message.mentions)
intersection = set(map(lambda m: m.id, message.mentions))
with open("nopinglist.json") as f:
data = json.load(f)
no_ping_list = data["no-ping-list"]
if intersection == True:
#stuff
else:
pass
No, you need 2 variables:
- a set containing the IDs of the people who can't get pinged
- a set containing the IDs of the people who were pinged in a certain message
mentioned_set = set(map(lambda m: m.id, message.mentions))
with open(...) as f:
no_ping_list = ...
no_ping_set = set(no_ping_list)
if mentioned_set & no_ping_set:
# do something if they were pinged
else:
# do something else, or just ignore
use and not &
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{2, 3, 4}
Hm that's not what we're looking for
sets are useless
no?
So like this?
mentioned_set = set(map(lambda m: m.id, message.mentions))
with open("nopinglist.json") as f:
no_ping_list = data["no-ping-list"]
no_ping_set = set(no_ping_list)
if mentioned_set and no_ping_set:
await message.delete()
else:
pass
whats the issue though?
He crossed it out lmao
sets are used to remove duplicates from a list so theyre good ngl
just use list subtraction
and frozen sets

Use & not and
oh ok
what? that works?
and if you're just going to do else: pass just leave it out
aka ive never used it lol
!e
print({1, 2, 3} & {2, 3, 4})
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{2, 3}
pretty nice





