#discord-bots
1 messages Ā· Page 935 of 1
This isn't where you're creating the buttons?
I hid the token
inefficient way, but make a list of restricted words, loop through them, and check if its in the message
oh wait
is it possible that the bot can use server emojis without having nitro?
yes
do you know how :)
client.get_emoji(NUMBER)
i forgot embed=emb
right click and open image and youll find the id number in the url
i think your bot needs to be in server of emoji you're trying to use
uh same error
@dull terrace
yeah it's about components, probably because you haven't put them in a list
do u mean this
hm?
idk how disnake works but when i make a button it's components=[ActionRow(Button(style=2, label="this is an example, custom_id="butt monkeys"))]
Whom? I just don't understand a little
bruh
oh and style
blurple
so
@slate swan nothing all fixed
Stop using 3rd party libraries, go for a fork or discord.py master branch
disnake is third party?
Example.
Is that Disnake?
yes
how to import this into a message?
..
How did you import Button class?
?
Ok nvm, you won't use components for sending a view, it's .send(view= ViewClass())
yes
components is used for an ActionRowBuilder
emoji = client.get_emoji(id)
await message.channel.send(content=f"{emoji}")
wait
i think you just string it
i put component there by mistake tf
already tried
instead of view
@dull terrace@slate swan
thats the issue ig
how do I add category's to the help command? I always used groups, I wanna modify it now
You can't use that @button decorator there then
it sends instead "None" of this emoji
It's meant for views
why content kwarg
yes i was using views
how do I add category's to the help command? I always used groups, I wanna modify it now
it works
you're not fetching the emoji correctly
is it because I'm using commands and not client?
don't need it but you can put it, i think certain circumstances you do need it
you're probably using bot or client, look for where ever you defined client = commands.Bot(command_prefix="your prefix")
I'm using bot
then change client to bot
do you have the correct emoji number and passing it as an int?

https://cdn.discordapp.com/emojis/652247559909277706.webp?size=96&quality=lossless > id = 652247559909277706
await ctx.channel.send(content=f'not working, sorry {sad}')``` @dull terrace
hmmm
and when I call this command it sends not working, sorry None
well the only thing that could be is that it's not getting the emoji
not sure why that is
try with different emojis
make sure that sad isn't a function name or defined elsewhere
oooh I copied the ID from the message and not from the emoji
@dull terrace
š
oof
bro discord just literally pranked me
it pranks us all
why do you async run client.run()
it's a normal func
dunno
what can't you do on client with cogs
oh that
Why not just use commands.Bot?
nah it really doesn't have cogs
command handling is only part of what commands.Bot does
cogs are a perfectly good reason to use it
it would be better if you didn't need to for cogs I agree
how to send a message which only the executer can see?
You can send ephemeral messages in response to interactions only, so if someone runs a slash command or clicks a button you can use interaction.response.send(..., ephemeral=True)
I mean the author
because you are using the Member class itself rather than using an instance of it
rip the reply didnt even work
so I should do that ?
yeah
How can I put time in the bot status
use the datetime module....
whats that
import datetime
I mean docs on it
!d datetime.datetime.utcnow() this returns the Universal Time
No documentation found for the requested symbol.
classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.
This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now").
Warning
Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
you can use the strftime attribute on this to format your time
and use pytz with datetime for different timezones
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.dnd, activity=discord.Game(f'Time {datetime.utcnow()}'))
print(f"Logged in as {client.user}")```
like this?
commmands
maybe you know, mention a member when you invoke the command ?
thanks my bad
??
in your command member is a required argument, so just by doing prefix userinfo will not do anything, you can do member: discord.Member = None and make an error handler though or a check
await client.change_presence(status=discord.Status.dnd, activity=discord.Game)```
How can I make it watching instead of playing
Quick question how do i unban a user using their user ID?
user.unban()
Thatās pretty much the only way to do so through a command
tried that keeps saying user not found
hm
you would have the match your member parameterās discriminator and name to the user (discord account) discriminator and name
discord.ActivityType.watching
ctx.guild.unban(userid)
or am i wrng
im tired rn my brain is just wandering in pain
that is if he had a name
he said id
bro every discord account has a name
oh didnāt see that lol
lol
Lmao im tryna keep it simple using ID
gave me this error
Itās only a few lines for what Iām suggesting
but for whatever reason it does not find the ID
await client.change_presence(status=discord.Status.dnd, activity=discord.ActivityType.watching(f'Time{datetime.utcnow()}'))```
How am I support to put strftime in it
well u need the user id, if u dont have it, ya need to do it like moai said
yeah i pass the id into the command
has anyone used fastapi for a bot dashboard?
but apparently it does not find the user
I think my approach would be the fastest and easiest
and idk if its me but i couldnt find the api
user = bot.fetch_user(id)
hello ashley
await ctx.guild.unban(user)
well of course, you're not pinging anyone you better stick to make member required argument
this is an unban command?
!e
from datetime import datetime
print(datetime.utcnow().strftime("%H:%M:%S"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
15:21:29
unban by id yes
the time is wrong
it will work properly for you though
why not discord.Object?
I just made it as simple as possible

i mean...
not my fault 
and i have never used discord.Object šæ
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create āminiatureā versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the objectās hash.
i'd suggest discord.Object, saves an API call for one and is just more efficient i heard
ahh ok
i mean efficient in what sense
to who was asking for it, it'd be ```py
async def unban(ctx, member_id : int):
member = discord.Object(member_Id)
await ctx.guild.unban(member)
both do their job
yeah...even though two things do the same it doesn't mean one is not better than the other
Itās essentially the same thing, though.
then explain how x is better than y
Uh
u can directly do member_id: discord.Object iirc
I mean if you read above youād see that he said it makes an unnecessary api call that just gets wasted.
But idk never tried
I doubt thatās a thing
line 17, in on_ready
await client.change_presence(status=discord.Status.dnd, activity=discord.ActivityType.watching(datetime.utcnow().strftime("%H:%M:%S")))
TypeError: '_EnumValueBase_ActivityType' object is not callable```
yeah don't think so
idk never made an unban command ĀÆ_(ć)_/ĀÆ
yes what Tylerr said, discord.Object doesn't use an API call
uh
api call that just gets wasted
lmao, it makes sense but in the same time it's just bs, unless your bot is in more than 500k servers, which i doubt anyone here has a bot that exceed few k 99% at their first project, so it won't affect them at all
Thatās a shitty way to think of it
np
bot.timer = 0
@bot.command()
async def addtimer(ctx, duration):
bot.timer += 1
await asyncio.sleep(int(duration))
bot.timer -= 1
@bot.command()
async def myrunningtimers(ctx):
await ctx.send(f"{bot.timer}")
Does anyone know how i could make it so if i have a timer running and he does the myrunningtimers command it wont show one for him?
Just because your bots not big doesnāt mean you shouldnāt avoid stuff like that.
Basically, i want to reach the goal so everyone can have their own timers running
Good developers actually optimize their code beforehand so they wonāt have to waste time doing it later š
I mean it could be like saying [i for i in range(1000)] and (i for i in range(1000)) both get the same thing done so they're equal one is not better than the other but the generator is better
someone help me with this
thatās a generator?
yeah
(expression for elem in something) is a gen exp
!e
print(type((i for i in range(5))))
@sage otter :white_check_mark: Your eval job has completed with return code 0.
<class 'generator'>
oh ok.
Generator expressions are what everyone thinks tuple comprehension are
Thatās what I was just thinking it was Iām not gonna lie.
donāt think tuple comps exist
!e
a = (x for x in range(10))
print(a.__next__())
print(a.__next__())
print(a)
@slim ibex :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | <generator object <genexpr> at 0x7f909c843ca0>
line 17, in on_ready
await client.change_presence(status=discord.Status.dnd, activity=discord.ActivityType.watching(datetime.utcnow().strftime("%H:%M:%S")))
TypeError: '_EnumValueBase_ActivityType' object is not callable```
One more question do you know how i would convert the UID into the Username?
nope
@client.command()
async def frame(ctx):
message = await ctx.channel.fetch_message(ctx.message.reference.message_id)
if message.author.id == 646937666251915264:
reg = re.compile('<@!?([0-9]+)>')
matches = reg.findall(message.content)
await ctx.send(f"User: {matches}")```
Why i get as output ```[]```
Nws thanks for the elp though
Read the error. discord.ActivityType.[ā¦] isnāt a coro
then what would I use
Does anyone know how i can convert the user id into a name of someone who is not in the guild?
because I don't know how it works
Anyways, has anyone made a dashboard with fastapi?
help pls
He doesnāt try to use it as a coro tho? Thereās no await? The only thing that gets awaited in that line is the change_presence
what is message_id attribute?
He is using a coro for it. It literally has ()
that has to be the dumbest shit Iāve ever read in this channel
() implies itās a callable
š
LMAO
!d discord.MessageReference.message_id
The id of the message referenced.
embed
Meaning it can also be a function.
!d discord.MessageReference
class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)```
Represents a reference to a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.5.
Changed in version 1.6: This class can now be constructed by users.
oh didn't know that existed
# do this
await client.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name=datetime.utcnow().strftime("%H:%M:%S")))``` try this and see if it works, I donāt use statuses on my bots much but
And the error means is saying ActivityType is not a callable and that is an enum.
Itās a joke bud
you should be knowing that a code is never fully optimized there will always be quite periodic updates, 100% when we talk about code interacting with APIs that are periodically updated. tell me an app or anything online that reached perfection, at the point where "yeah, we optimized our code beforehand and now it's all perfect" at this point you just have sweet dreams
i sure hope so.
^
yes it works
Jesus Christ man.
K
ctx
I never said you had to optimize 100%. I said if you have the chance you should try.
Cya
why do it later when your bot gets big when you can do it now and save yourself some effort later.
You're making it harder on yourself
For no reason at all.
yeah if I may, you're completely thinking of this wrong
š Ash coming to run the ot command
I'mma delete the messages instead
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
try defining the time inside a var and use that variable
Wait, it hasn't implemented member.timeout?
š
no thatās just another useless abstraction
I just hate it when discord turns off ping automatically
right
Member.edit(timed_out_until) was the implementation he gave us
Well that's is cool
u have the member object so get the username. u have the time till which the member is muted so u get the time of mute. reason is just another kwarg in the command
no
uh?
weirdo ĀÆ_(ć)_/ĀÆ
gib code not shit Docs
No thanks

where can I find timestamp styles
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
API Reference: https://github.com/discord/discord-api-docs/blob/ff4d9d8ea6493405a8823492338880c47fb02996/docs/Reference.md#timestamp-styles
See discord.utils.format_dt for the discord.py implementation.
https://discordpy.readthedocs.io/en/master/api.html#discord.utils.format_dt
uh not much, isnt there more?
Or that, yea
that is all
how can I get 12hr clock style
i do not believe you can
twenty four hour only as short or long time
I saw one on it thought cant remember
Im not sure if its timestamps styles smth related like %d or smth
ok nvm found what im looking for
Itās locale specific
do u happen to know how i can get one without the .882340
Depending on where you live the clock will show 24h/12h
timestamp
Guys is it possible to use the timeout feature using python?
i believe so
sometimes my json glitch and dump 2 same
key value
Do you know where i could take a look at it / learn how to do it?
discord.py api docs, timeout search it up
Didnāt you just ask this question?
how do i get a role then?
No-?
Main
2.0?
anyone know the code to the timestamp without the .882340?
Or 1.7.3?
Im usin Python 3.9 atm
i'm searching for it as well
i was searching for hours yesterday
absolutely nothing
that's so annoying when you searching for something for hours without getting any positive result
yeh
await client.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name=datetime.utcnow().strftime("%I:%M %p")))```
How can I change time to est
estnow() i guess?
you can try pytz
!pypi pytz
you can see examples on the docs, i'm not that familiar try it and check
which one do you guys like?
1st
ty
Strftime?
Idk if i spelled it right lmao
Both
lower s
if role.position > ctx.author.highest_role:
would that work ?
oh well, its top_role not highest_role
its top_role, okay
nice
No need
discord.Role impl's gt or lt
So you can just do if role > ctx.author.top_role
what does this mean?
gt = >
lt = <
oh you mean greater than or less than
greater than less than
ily, no homo

cool didn't know that
sus
how to edit a roles name?
Lmaooo i sent that cuz i didnt know what to say so
!d discord.Role.edit
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
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.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
pytz is confusing
first, second one its difficult to see the red X
red emoji on red button is not the best idea so text is better
everything is confusing at first
just gotta get used to it ig
you got a point 
await role.edit(colour=color)
i typed:
,role color muted #800080
1, 100%
it knows the role but the color didnt set?
Its because the color should be int?
so no #?
For example : py @bot.command() async def mycommand(ctx, color, otherparams): em = discord.Embed(color = int(color, 16))

with discord.py, how do i get a user object from a guild? i'm trying to make it so a command sent in the dms can change the role of the user in the server, this is what i have right now: bot.get_guild(guild_id).get_user(author.id).roles
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
thank you!
no worries
does discord.py support slash commands?
@bot.command()
async def ŠæŃŠµŠ“Ń(ctx, member: discord.Member = None):
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR)""")
base.commit()
print(1)
global warnings
warnings = cursor.execute("SELECT * FROM warning WHERE userid = ?", (ctx.author.id,)).fetchone()
print("ŃŠ°Š±Š¾ŃаеŃ")
if member is None:
await ctx.send(f"ŠŃŠ¾Š²ŠµŃŠŗŠ° по базе ГаннŃŃ
...\nŠŃŠ¾Š²ŠµŃŠŗŠ° ŠæŃŠ¾Ńла.\n{ctx.author.name} Š£ Š²Š°Ń {warnings[2]} ŠæŃŠµŠ“ŃŠæŃежГений")
else:
await ctx.send(f"ŠŃŠ¾Š²ŠµŃŠŗŠ° по базе ГаннŃŃ
...\nŠŃŠ¾Š²ŠµŃŠŗŠ° ŠæŃŠ¾Ńла.\n{member.name} Š£ Š²Š°Ń {warnings[2]} ŠæŃŠµŠ“ŃŠæŃежГений!")ā
Help me please.Why when a member is mentioned, their warn are shown??
The 2.0 version supports it
Why are u using global keyword?
Ig it might break ur codeš«±šæāš«²š¾
Thank
can u point to the docs? https://discordpy.readthedocs.io/en/latest/api.html?highlight=slash doesnt show much
never used dpy 2.0 but i heard that u need something called tree to create slash commands and app commands
hmmmm
Ye š¤·š¾
disnake is the best
change ma mind
maybe
!d disnake.ext.commands.Bot.slash_command
@slash_command(*args, **kwargs)```
A shortcut decorator that invokes [`slash_command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.slash_command "disnake.ext.commands.slash_command") and adds it to the internal command list.
I forgot to remove it, so why, at the mention, my number of warns is shown@slate swan
Why BotMissingArgument doesn't work
Ig its because u have something {warnings[2]}
I really dont know what u want
Why doesn't it work?
To show how many warns the user has when he is mentioned@slate swan
But it doesnt work?
Thank
no, it shows only its own varnas even when the user is mentioned@slate swan
Why does this pop up for me?
"The system could not find the specified path"
Can u !paste ur code cuz im on mobile
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Idk tbh, i've tried that but it doesnt work? š¤·š¾
you're french?
import requests, discord, os, random, subprocess
from startBot import *
from commands.normal import *
class gradientFunctions:
async def SendGradientSingle(ctx, RGBValues:str):
Sensitive_Chars = ['"', '@','#','{','}',';','-','>','<','`','*','=','+','curl','\\']
if len(RGBValues)>=7:
await ctx.send(" Please provide a 6-digit hex character.")
return
for x in RGBValues:
for f in range(0,len(Sensitive_Chars)):
if x in Sensitive_Chars[f]:
await ctx.send(" Your input contains an invalid character.")
return
else: pass
random = random.randint(1,900)
s = subprocess.getoutput(f"curl -X GET https://singlecolorimage.com/get/{RGBValues}/400x100 --output temp.{random}.myTemporaryFile")
await ctx.send(f"Output\n{s}",file=discord.File(f'temp.{random}.myTemporaryFile'))
return
Can anyone help me with why the program is not working after s = os.system(f"curl -X GET https://singlecolorimage.com/get/{RGBValues}/400x100 --output temp.{random}.myTemporaryFile")
No, but i understand some :)
my bad because I thought you we're french with your pfp and your tag
Its alr but i understood wut u said
!d discord.ext.commands.BotMissingPermissions
exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)```
Exception raised when the botās member lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
@slate swan this might help u?
Can anyone help?
@slate swan
@bot.command()
async def ŠæŃŠµŠ“Ń(ctx, member: discord.Member = None):
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR)""")
base.commit()
print(1)
global warnings
warnings = cursor.execute("SELECT * FROM warning WHERE userid = ?", (ctx.author.id,)).fetchone()
print("ŃŠ°Š±Š¾ŃаеŃ")
if member is None:
await ctx.send(f"ŠŃŠ¾Š²ŠµŃŠŗŠ° по базе ГаннŃŃ
...\nŠŃŠ¾Š²ŠµŃŠŗŠ° ŠæŃŠ¾Ńла.\n{ctx.author.name} Š£ Š²Š°Ń {warnings[2]} ŠæŃŠµŠ“ŃŠæŃежГений")
else:
await ctx.send(f"ŠŃŠ¾Š²ŠµŃŠŗŠ° по базе ГаннŃŃ
...\nŠŃŠ¾Š²ŠµŃŠŗŠ° ŠæŃŠ¾Ńла.\n{member.name} Š£ Š²Š°Ń {warnings[2]} ŠæŃŠµŠ“ŃŠæŃежГений!")ā
the problem?
^
Why does this pop up for me?
"The system could not find the specified path"
i dont quite understand what he means tbh
Me neither
what are you trying to do?
because the system can't find the specified path

run the bot, it starts normally, but it knocks out such a problem
i wish i could help but i only speak english and spanish
so i dont know what the tb means
Open cmd inside the bot folder?
yo btw there's no text chanel to advertise right ?
in this server no
can you advertise anywhere in this server no
k
Advertising projects or servers?
u got any server where u can advertise python stuff
!rule 6
this is the rule btw
ok bro i was just asking
Idk tbh
i know i just wanted to prove my point lol

uhh i'm having a huge problem, if I enable the command in one server it will activate, but if I do it on another server it desactivate it
for people that wants to see config.py line
Eh ig u need to use a db for that
how
so u can check if the guild has that option on or off
If its on then the bot is going to do stuff if its off then it will return or whatever you trying to do
Can anyone help me with discord.py, a image is not sending
!code
import requests, discord, os, random
from startBot import *
from commands.normal import *
class gradientFunctions:
async def SendGradientSingle(ctx, RGBValues:str):
Sensitive_Chars = ['"', '@','#','{','}',';','-','>','<','`','*','=','+','curl','\\']
if len(RGBValues)>=7:
await ctx.send(" Please provide a 6-digit hex character.")
return
for x in RGBValues:
for f in range(0,len(Sensitive_Chars)):
if x in Sensitive_Chars[f]:
await ctx.send(" Your input contains an invalid character.")
return
else: pass
ranNum = random.randint(1,1000)
with os.system(f"curl -X GET https://singlecolorimage.com/get/{RGBValues}/400x100 --output temporary.{ranNum}.myTempFile.jpg") as Request:
await ctx.send(" R G B ",file=discord.File(f"D:\\Gradient Bot\\src\\temporary.{ranNum}.myTempFile.jpg"))
os.remove(f"temporary.{ranNum}.myTempFile.jpg")
return
If you're using that bot in 1 server then u dont need a db
I want it to make public so it is a huge problem
I don't know how to make a db
SQLite is a good starting point
@commands.has_role("Support, Leaf")``` uh not working
its 1 string
and thats not the deco for multiple roles
"Support", "leaf"
sopy @commands.has_role("Support", "Leaf")
ah ok
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
is the deco you should use
alright
so if I used role id 492212595072434186 i dont have to put ""
the author who invoked the context of the command
no it doesnt need to be a string
alright
it has to be an int
int?
!e print(type(1))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'int'>
@commands.has_any_role(492212595072434186)```
a number without a decimal point
yes
Ye ye
hey culd someone help me out with hosting a dc bot for free?
cause i hv got the code working it just the hosting part that's left
i doubt someone would host your bot for free
well most of them arent really good tbh
i've heard heroku is gud but not sure how to host a bot there
and in replit, if we edit the bot its difficult to re-host the bot
you can but its not really meant for that
heroku isnt ment to host discord bots
o
It's not good
"Good free hosting" is a bit of an oxymoron
You either get frankly bad but free hosting, or high quality hosting that's paid
oh
no
Cool, yeah have you tried importing your tree instance?
!pip PyDcDB 
wait ashley didn't you do some economy bot shit cuz all the people want it
yeah lol
Or, alternatively, you can use discord.app_commands.CommandTree.add_command() in your main file
I think it'd be better if you imported your slash command class/method instead
and used .add_command() on it
Tell
there's examples in there
Well would it be bad?
Uh
Importing functions/classes between files isn't necessarily bad
If we're talking about performance, it's all done within memory so it's blazing fast
?
lol
Well cogs do exactly that
Behind the scenes cogs are doing the same thing
For the time being there's no multi-file functionality
nothing 
You could do it dynamically as well, with a for loop of sorts
what?
Perhaps, but it would be easier to just do it manually
You'll only be overcomplicating it
"Slash command cogs" or not you're still importing the slash commands
It's only a matter of ease of use
i didnt destroyed it i rewrote it because it was destroyed 
It doesnāt have to be designed like a cog
?
ready i fixed
Each command can just be in its own file
or each group
Make it whatever you want
Or create a class that acts similar to a cog where you iterate through its attributes to filter out its commands
importing can be fully dynamic tho

You are not allowed to use that command here. Please use the #bot-commands channel instead.
jesus typing on a phone sucks
importlib.import_module(name, package=None)```
Import a module. The *name* argument specifies what module to import in absolute or relative terms (e.g. either `pkg.mod` or `..mod`). If the name is specified in relative terms, then the *package* argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. `import_module('..mod', 'pkg.subpkg')` will import `pkg.mod`).
The [`import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module") function acts as a simplifying wrapper around [`importlib.__import__()`](https://docs.python.org/3/library/importlib.html#importlib.__import__ "importlib.__import__"). This means all semantics of the function are derived from [`importlib.__import__()`](https://docs.python.org/3/library/importlib.html#importlib.__import__ "importlib.__import__"). The most important difference between these two functions is that [`import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module") returns the specified package or module (e.g. `pkg.mod`), while [`__import__()`](https://docs.python.org/3/library/functions.html#import__ "__import__") returns the top-level package or module (e.g. `pkg`).
i typed it wrong again š
This is the same thing discord.py uses under the hood for cogs as well iirc
What I used to do is define a __all__ variable in the file declaring the names of the objects i wanted exported
Then after importing the module I would iterate through __all__ and use getattr() on the module
If you want to reload your app during runtime, you can do so by deleting any python files that you want to be reloaded from sys.modules and then reimport it with importlib
!d sys.modules
sys.modules```
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail. If you want to iterate over this global dictionary always use `sys.modules.copy()` or `tuple(sys.modules)` to avoid exceptions as its size may change during iteration as a side effect of code or activity in other threads.
What do you mean by group?
Itās a dict[str, ModuleType]
Do you mean like subcommands or?
It would be funny if you could with open() a python file and make it act as a module
That's one way
Another way would be to dynamically import all slash command callbacks, and in your main file (which has tree instance), use add_command()
You could copy the cog implementation and modify it to work with slash commands yeah
You could also have something like a setup() function that can add multiple slash commands per file, so that can double as "groups" like you mentioned
The add_command way would increase your startup time
Actually, not even sure about that
Because either way commands get registered on runtime
How?
Because of how decorators work
Well doesn't the decorator call add_command?
Yea\
!d discord.app_commands.CommandTree.command
command(*, name=..., description=..., guild=..., guilds=...)```
Creates an application command directly under this tree.
yeah that
add_command()ās speed is negligible
If anything, you will experience performance issues when importing modules
Python is pretty slow at this
Importing will barely affect your performance
Nah, if you're using slash commands that's not necessary
I can't remember the exact steps, but I do remember there is only two steps with importing and it barely costs anything
@commands.has_permissions(ban_members = True)
I am typing this right correct?
For whatever reason it say's i do not have permissions
as server owner lol
For some reason I feel like this might cause a namespace pollution
š best of luck
Probably not though
More info?
@commands.command(name="ban")
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.has_permissions(ban_members = True)
It says i am missing permissions
however as server owner i have the permissions to ban someone
however the bot decides otherwise?
Any idea why?
Try this @commands.has_guild_permissions(ban_members=True)
"Note that this check operates on the current channel permissions, not the guild wide permissions."
Since you are mixing stuff
Namespace pollution just means that the namespace is filled with wrong information or etc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Like, for an instance rin.aiohttp is a problem I had because I didn't have a proper __all__
Still the same
You could also have missing packages if your namespace is polluted
But this isn't a permissions error, the bot isn't allowed to do whatever you are doing inside the command.
Likely you are trying to ban a member that is higher than the bot.
Hello! I'm trying to make a command that gives a user a category of their own, but for some reason it's not letting them edit the category at all, despite the fact that it should give them the perms for that. Is this a discord issue, or something I did wrong myself?
@bot.command()
async def category(ctx, *category_name):
if category_name==[]:
category_name = random.choice(open('data/WORDS.txt').read().split('\n')) + '_' + random.choice(open('WORDS.txt').read().split('\n'))
else:
category_name=' '.join(category_name)
category = await bot.get_guild(917640265475440681).create_category(category_name)
await category.set_permissions(bot.get_guild(917640265475440681).default_role, read_messages=True,send_messages=True,add_reactions=True,attach_files=True,create_instant_invite=False,manage_channels=False,manage_messages=False,manage_permissions=False,read_message_history=True,view_channel=True,mention_everyone=False,connect=True,speak=True,stream=True)
await category.set_permissions(bot.get_guild(917640265475440681).get_member(ctx.author.id), read_messages=True,send_messages=True,add_reactions=True,attach_files=True,create_instant_invite=True,manage_channels=True,manage_messages=True,manage_permissions=True,read_message_history=True,view_channel=True,mention_everyone=False,connect=True,speak=True,stream=True)
await category.set_permissions(bot.get_guild(917640265475440681).get_member(431544605209788416), read_messages=True,send_messages=True,add_reactions=True,attach_files=True,create_instant_invite=True,manage_channels=True,manage_messages=True,manage_permissions=True,read_message_history=True,view_channel=True,mention_everyone=False,connect=True,speak=True,stream=True)
await bot.get_guild(917640265475440681).create_text_channel(category_name, category=category)
await ctx.send(f'Your new category "{category_name}" has been created <@{ctx.author.id}>!')
The Bot is an Administrator while the account i am trying to ban my alt has no perms
Could you show what you are doing inside the cmd?
Ah got it-
The Role was simply below the person i was trying to ban
shoot- howd i miss that-
Crap-
@cloud dawn Ty For your help lmao
š¤
400 errors are always because the bot isn't allowed to do something. The more you know.
Personally like adding a logger, kwargs according to that pep person is smashed against each other intents=None. The class name is also a bit weird since it doesn't describe what this class is.
async def giveaway(self, ctx, time: int, *, prize):
giveawayembed = nextcord.Embed(
title="š New Giveaway! š",
color=0xfd9fa1
)
giveawayembed.add_field(name="Prize", value="{}".format(prize), inline=False)
giveawayembed.add_field(name="Hosted by", value=f"{ctx.author.mention}", inline=False)
giveawayembed.add_field(name="Ends in", value="{}s".format(time))
msg = await ctx.send(embed=giveawayembed)
await msg.add_reaction("š")
await asyncio.sleep(time)
msg = await msg.channel.fetch_message(msg.id)
my giveaway code lets me set time limits in seconds only, how can i make it so that it accepts arguments like 1h, 3d, etc?
!source tempmute
Temporarily mute a user for the given reason and duration.
https://github.com/python-discord/bot/blob/main/bot/converters.py#L322-L361
Not an easy task I will tell you that.
yeah it looks really complicated 
How i get name and # with regex?
Like <@!?([0-9]+)>
Pretty simple one way is regex
what is regex?
regular expression
you can just 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.
mariadb can i use this db in pycharm
I do it with embed
because i dont finde the hoste name or the port
do you have already started with the bot?
Your IDE
!source jail
Unable to convert 'jail' to valid command, tag, or Cog.
!source [source_item]
Can also use: src
Display information and a GitHub link to the source code of a command, tag, or cog.
create a bot event
yeah
first you need that the bot knows on which guild(server) he needs to send this message
guild = bot.get_guild(your server id)
@bot.event doesn't "create a bot event"
i mean a event for the bot
What
It's a decorator that registers an event to listen to
!d discord.ext.commands.Bot.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.10)"), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") is raised.
Example
```py
@client.event
async def on_ready():
print('Ready!')
```...
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
{len(client.users)}
``` Why does this return me 1?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
what about sublime
Bro why are you reading back chat šæ
its a coroutine of the member class
Anyone? this randomly stopped, it used to work.
you didnt answer my question you do know thats impolite right?
!d discord.ext.commands.Bot.users
property users```
Returns a list of all the users the bot can see.
you need intents
but it used to work, so i dont know why it stopped working
as my bf said (bestfriend)
š¤Ø
show code
sure

await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching,name = f'{servers} servers and {len(client.users)} members'))
your bot constructor
show that
yes you need to add an instsnce if the intents class in the intents kwarg
pls read this
@slate swan ty 

await member_obj.timeout(...) in this case member_obj should be a member obj which then you can use the coroutine on the class since the coroutine is a method of the member class
How would i make a global database attribute for the bot (asqlite/aiosqlite) in dpy 2.0? I tried using the main async function but that for some reason didn't work
did you tried bot variables?
there isnt a release on pip its only 1.7.x
2.0 (Installing/Upgrading from GitHub):
# With non-voice support:
py -m pip install -U git+https://github.com/Rapptz/discord.py
# With voice support:
py -m pip install -U git+https://github.com/Rapptz/discord.py#egg=discord.py[voice]```
- Linux/Mac:
```# With non-voice support:
python3 -m pip install -U git+https://github.com/Rapptz/discord.py
# With voice support:
python3 -m pip install -U git+https://github.com/Rapptz/discord.py#egg=discord.py[voice]
Notes:
- Make sure you have git installed and have git in your PATH. To check if git is installed and is in your PATH, just do git --version. To install git, visit https://git-scm.com/
- You need Python 3.8 or above to install 2.0
on github
yes
have you tried subclassing the Bot class and then making a method which returns a connection?
keep_alive()
NameError: name 'keep_alive' is not defined``` can anyone help?
!e a()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'a' is not defined
its not a defined function
can someone give an example how to use the timout function with ctx or any param?
how would that matter just set an argument or if its on message just get the author since it returns a member obj
!d discord.Message.author
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
Changed in version 2.0: `member_id` parameter is now positional-only.
really depends on the situation
await ctx.author.timeout_for
why wont this work tho member doesnt have this attribute how can i use it otherwise here
1.7.3 doesnt have that method
you need to use a fork or main
yeah im using 2.0
did you uninstalled 1.7.3?
how can i check the ver?
print(discord.__version__)
not sure if dpy has that method
it prints out 1.7.3
wait ima just reinstall everything
youre not using main then.
!pypi py-cord
kinda bad fork imo
Why? I dont know much bout it
i like disnake much more than py-cord
@bot.command()
async def info(ctx, arg=None):
author = ctx.massage.author
if arg == None:
await ctx.send(f'{author} ŠŠ²ŠµŠ“ŠøŃŠµ: \n !info general \n !info commands')
elif arg == 'general':
await ctx.send(f'{author} In future')
elif arg == 'commands':
await ctx.send(f'{author} !test - Online bot check\n !status - My warnings')
else:
await ctx.send(f'{author} no such command...')
Why doesn't this code work?
you should do if arg is None
and you did cts not ctx
its implementation on methods is trash
itās message, not massage
if not arg:
genius
thanks
itās
message, notmassage
@azure tulip
you love massages dont you
š¤Ø

but this code works for him and I rewrote it and it doesn't work for me
you spelt message wrong
ctx.message, you got a typo
š bro, he has written 'message' even in the tutorial
pls increase your video resolutoin or make it full screen to view it clearly š
or even better dont follow yt tutorials
+1
but could be that he's a beginner.. or not familiar with OOP (not judging btw)
so let him play around
i fix this typo
and?
you should download pyright so you can have a linter
Pyright doesn't give intellisense
anyone know how to make a enable/disable command when u run it the command doesnt work till u enable it
im so confused on what a linter and intellisense means
You can set enabled = False
You can get the Command object using ctx.command
Linters do code analysis, intellisense provides coc and general info
Pyright would more fall under the linter category, itās a type checker
ic thx

@bot.command()
async def info(ctx, arg=None):
author = ctx.message.author
if arg == None:
await ctx.send(f'{author.mention} Enter: \n !info general \n !info commands')
elif arg == 'general':
await ctx.send(f'{author} In future')
elif arg == 'commands':
await ctx.send(f'{author} !test - Online bot check\n !status - My warnings')
else:
await ctx.send(f'{author} no such command...')
It work!
Thanks to everyone who could
this will help you in the future^
I'm download, thanks for the advice
Why not subclass helpcommand?
I'm new, I'm only studying programming for the second day and I do everything according to the guides, if you can do subclass helpcommand at once, then I will do it that way
copying from tutorials wonāt help you learn
hopefully you atleast know the basics like variables, functions, control flow, iteration, etc
!customhelp
Custom help commands in discord.py
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
Heres a guide for subclassing the help command
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(title='Missing Argument',description=f'You must include all arguments to do this command!')
await ctx.send(embed=embed)
c = ctx.invoked_with
c.reset_cooldown(ctx)
And, i keep getting this error: AttributeError: 'str' object has no attribute 'reset_cooldown'
!d discord.ext.commands.Context.invoked_with
The command name that triggered this invocation. Useful for finding out which alias called the command.
Yeah, invoked_with returns a string
hmm this worked before but then just started doing this like a couple hours ago
ok then

well, I donāt exactly copy, I study every little thing and the author of the video talks about everything, but as for variables and the like, I agree
that's good atleast youre trying to know how everything works and not only syntax

TypeError: edit() takes 1 positional argument but 2 were given```
await msg_id.edit("š GIVEAWAY ENDED š")
anyone know the error?
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
why so many pythons? which is the best to learn?
it really depends on which category you want to learn
I want to make discord bots and maybe websites in the future
well you can just learn web development and oop
Šk
this can help you with oop https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc
In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.
Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...
Thanks

Well, I'll look at a fresh head tomorrow, but now I'm going to sleep, good night)
Goodnight
Does anyone know how to make buttons using discord.py?
Im so stuck and I dont know how to
you need dpy 2.0
how do I install it?
do pip install git+https://github.com/Rapptz/discord.py is the command iirc
in cmd
if youre on windows
on mac
just do it where you install packages btw you need git but if you dont want to install git you can just install a fork like disnake with pip
I did it but now it gives this error
show
SyntaxError: invalid syntax
alanabeaton@sonic lintels-Air Auora Bot % /usr/local/bin/python3 "/Users/alanabeaton/Auora Bot/main.py"
Traceback (most recent call last):
File "/Users/alanabeaton/Auora Bot/main.py", line 66, in <module>
bot.run("token")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 709, in run
asyncio.run(runner())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 706, in runner
await self.start(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 680, in start
await self.connect(reconnect=reconnect)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 617, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord ā whether it's a bot or a game or whatever your wildest imagination can come up with.
you need to enable the intent
How?
in the dev portal
ok
I did it but it still gives the same error
do you have all of them on?
:))
@slate swan I want to make a guided breathing bot
So that it responds in a thread with buttons
but Im still really unsure what to do
youre unsure with?
Im just unsure how to make it
well all you have to do is subclass view and then make callbacks for buttons and you send the view
Ill try
heres an easy example
class ExampleView(discord.ui.View):
def __init__(self) -> None:
super().__init__()
@discord.ui.button(label='Button', style=discord.ButtonStyle.green)
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.send("You pressed the button!", ephemeral=True)
self.stop()
@bot.command()
async def button_example(ctx: commands.Context) -> None:
await ctx.send("Heres a message with a button!", view=ExampleView())
# this command is outside of the view ^
Thats reall helpful thank you!

on an interaction?
!d disnake.Interaction.send
await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message") or [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
If the interaction hasnāt been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message"). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
Note
This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") object. If you need a message object, use [`original_message()`](https://docs.disnake.dev/en/latest/api.html#disnake.Interaction.original_message "disnake.Interaction.original_message") to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send") directly instead of this method if youāre sending a followup message.
the ephemeral kwarg
just set it to True
i said on interaction context doesnt have that kwarg and you cannot send an ephemeral message if its not on Interaction
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
on the button call back
good example here
?
ok?
show code
all of a sudden i cant turn on my bot even though i didnt change the code. how do i fix this?
show full tb
you got ratelimited
oh what do i need to do to get out of it?
Are you using replit?
Can I ask how to install pycord here?
you wait or just kill the terminal
yes im using replit
yes
Ok
Then the solution is to top using it
wouldnt recommend using pycord tho
I'm just trying to use slash commands but I'm using the original pythn
original python pardon?
shouldnt button come before interaction?
o wrong message
^
from one the person said in #help-pancakes I can't slash commands in the original version of discord.py
what*
yes you can.
wth
What's wrong with my code then AHSUBGSJND
care to share the traceback?
the line of code that's messed up?
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
I can't think straight hearing my sister kiss her boyfriend bruh
@slate swan For discord buttons, do you have any idea how to make it so only the author can react to the button and how to make a private thread with the author
I'm gonna go outside and go back to biking for a little
well you can just pass the ctx author to the class and then you can just check on interaction
How do I do that and how do I make it so they can only interact with the button once?
just stop the view with stop()
which is bound to an instance of View or the subclass of it ofc
!d discord.ui.View.stop
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
still really confused
sorry I have never worked with buttons before
This is an example, the author is able to react multiple times
which results in a spam
also other people can also react
class YesButton(discord.ui.View):
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
discord.ui.View.stop()
bot = GuidedMediationBot()
@bot.command()
async def breathe(ctx: commands.Context):
"""Starts a breathe for pressing."""
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton())```
class ExampleView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__()
self.author = author
async def on_interaction(self, interaction: discord.Interaction) -> None:
if interaction.author != self.author:
return False
return True
@discord.ui.button(label='Button', style=discord.ButtonStyle.green)
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.send("You pressed the button!", ephemeral=True)
self.stop()
@bot.command()
async def button_example(ctx: commands.Context) -> None:
await ctx.send("Heres a message with a button!", view=ExampleView(ctx.author))
# this command is outside of the view ^
heres an example
Ill try it ty!
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: init() takes 1 positional argument but 2 were given
show code
from discord.ext import commands
import discord
import time
class GuidedMediationBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('a.'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
# Define a simple View that gives us a counter button
class Counter(discord.ui.View):
# Define the actual button
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
async def breathe(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(view=self)
# Define a View that will give us our own personal counter button
class YesButton(discord.ui.View):
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
self.stop()
bot = GuidedMediationBot()
@bot.command()
async def breathe(ctx: commands.Context):
"""Starts a breathe for pressing."""
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
time.sleep(5)
await ctx.reply('Are you in a comfortable position?')```
do py def __init__(self, bot): self.bot = bot
no
its not a cog.
nvm
i thought it was
I havent made it into a cog yet
Im working in the main script for now
then Ill seperate it into cogs
you can get rid of that Counter class
I just did
show full tb, dont use time.sleep , my example isnt quite their which you would need everything thats their like the coroutine on_interaction and the author argument thats positional
Ignoring exception in command breathe:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 187, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/alanabeaton/Auora Bot/main.py", line 45, in breathe
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
TypeError: init() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: init() takes 1 positional argument but 2 were given
Im still kind of confused, sorry Im kind of new with this
you need the author argument.
Where do I give that argument?
in the class init
here the class initiate has the argument def __init__(self, author: discord.Member) -> None:
class GuidedMediationBot(commands.Bot):
def __init__(self, author: discord.Member) -> None:
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('a.'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')```
so would this be correct then?
no
in your View subclass
yes just name the methods differently
all of the components are bound to an instance of the class which you can get a list of them with children
yes
from discord.ext import commands
import discord
import time
class GuidedMediationBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('a.'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
# Define a simple View that gives us a counter button
# Define a View that will give us our own personal counter button
class YesButton(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
self.stop()
class IamButton(discord.ui.View):
# Define the actual button
@discord.ui.button(label='I am', style=discord.ButtonStyle.green)
async def breathe(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(view=self)
bot = GuidedMediationBot()
@bot.command()
async def breathe(ctx: commands.Context):
"""Starts a breathe for pressing."""
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
time.sleep(5)
await ctx.reply('Are you in a comfortable position?', view=IamButton )```
!d disnake.ui.View.children
The list of children attached to this view.
try it
Ignoring exception in command breathe:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 187, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/alanabeaton/Auora Bot/main.py", line 46, in breathe
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/abc.py", line 1403, in send
with handle_message_parameters(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 186, in handle_message_parameters
payload['components'] = view.to_components()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ui/view.py", line 224, in to_components
children = sorted(self.children, key=key)
AttributeError: 'YesButton' object has no attribute 'children'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'YesButton' object has no attribute 'children'
bro?
wait a second
š
Make sure you're subclassing button/view
you need to access the init of the parent class which is View to access children
And also call super().__init__()
very much so
im a good person
Where do I call it?
in your subclass initiate
In the yesbuttonclass?
in its initiate yes
ok
Ignoring exception in command breathe:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 187, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/alanabeaton/Auora Bot/main.py", line 48, in breathe
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/abc.py", line 1403, in send
with handle_message_parameters(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 186, in handle_message_parameters
payload['components'] = view.to_components()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ui/view.py", line 224, in to_components
children = sorted(self.children, key=key)
AttributeError: 'YesButton' object has no attribute 'children'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'YesButton' object has no attribute 'children'
Still the same error
code:
from discord.ext import commands
import discord
import time
class GuidedMediationBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('a.'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
# Define a simple View that gives us a counter button
# Define a View that will give us our own personal counter button
class YesButton(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
self.stop()
super().__init__()
class IamButton(discord.ui.View):
# Define the actual button
@discord.ui.button(label='I am', style=discord.ButtonStyle.green)
async def breathe(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(view=self)
bot = GuidedMediationBot()
@bot.command()
async def breathe(ctx: commands.Context):
"""Starts a breathe for pressing."""
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
time.sleep(5)
await ctx.reply('Are you in a comfortable position?', view=IamButton )```
its in the callback method
class YesButton(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__()
it should be done in the initiate dunder as shown above^
you never called the class lol
await ctx.reply('Are you in a comfortable position?', view=IamButton )
I did
Do I call it in the yesbutton class?
!e
def function() -> str:
return "Hello this function has a value of a string"
print(function)
print(function())
you see how one prints the memory location and the other prints the value of the function
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <function function at 0x7f2d051e3d90>
002 | Hello this function has a value of a string
Because I want it to act as a reply after the yes button
no in the kwarg in .send in the Context class instance
await ctx.reply('Are you in a comfortable position?', view=IamButton())
as so
Im really confused sorry
from discord.ext import commands
import discord
import time
class GuidedMediationBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('a.'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
# Define a simple View that gives us a counter button
# Define a View that will give us our own personal counter button
class YesButton(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__()
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
self.stop()
class IamButton(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__()
# Define the actual button
@discord.ui.button(label='I am', style=discord.ButtonStyle.green)
async def breathe(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Are you in a comfortable position?')
bot = GuidedMediationBot()
@bot.command()
async def breathe(ctx: commands.Context):
"""Starts a breathe for pressing."""
await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
time.sleep(5)
await ctx.reply('Are you in a comfortable position?', view=IamButton())```
This is my code, can you tell me what I should change
use asyncio.sleep btw
you really put to sleep whole code to breathe damn


that sounds sus