#discord-bots
1 messages · Page 1091 of 1
ye i got it now ty
on_event event 😳 😳
is pycharm modded professional worth getting?like should i download ?
just get github students plan and use it legally
what that i dont use git for much except backup data or git cli for heroku
doesnt matter, all it needs is
- a github account
- a proof that you're a student.
do they give free stuff?
thats all
cool lemme try
if u like pycharm too much and also work with other langs then yes, although there are better options
jetbrains professional IDEs
a free domain from namecheap
free microsoft azure credits
free digitalocean credits
and much more...
nice
Is this the correct code to
- Give the user a warn
@client.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, user: discord.Member,*,reason=""):
if reason == "":
embedVar8 = discord.Embed(
title=(f"Error"),
desription=("Please specify a reason!"),
colour=(0xff0000))
await ctx.channel.send(embed=embedVar8)
else:
embedVar9 = discord.Embed(
title=('**User Warned**'),
description=(f'{user} has been warned because: {reason}'),
colour=(0xff0000))
user_id = str(user.id)
if user_id in db:
db[user_id].append(reason)
else:
db[user_id] = [reason]
await ctx.channel.send(embed=embedVar9)
- Delete the mentioned warn a user has
@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
embedVar11 = discord.Embed(
title=(f"Removed warn of {user.name}"),
description=(f"Warn {n} of {user} removed!"),
colour=(0xff0000))
if user_id in db:
db[user_id].pop(reason)
await ctx.channel.send(embed=embedVar10)
- Show the list of warnings the user has
@client.command()
@commands.has_permissions(administrator=True)
async def warnings(ctx, user: discord.Member):
warnlist = db[str(user.id)]
embedVar10 = discord.Embed(
title=(f"Warnings of {user.name}"),
description= "\n".join(f"{i}) {r}" for i, r in enumerate(warnlist, 1)),
colour=(0xff0000))
await ctx.channel.send(embed=embedVar10)
Hey, this is my command, Please see if its correct
yeah cause you sent a message object
sad, i dont have a proof of being s student
oh ok
you are looking for message.content maybe
even a screenshot of your profile on your school's website works
message.channel.send
Please tell me why he combines the nickname and the reason in one message and displays an error?
👀 i thought it was only id cards
Can someone help me with the 2nd one?
nah, i just used the same as what i just said 😂
xD
my school is not there

@commands.has_role(982744620792426537)
@commands.command(name = "бан", aliases = ["забанить", "ban"])
async def command_clear(self, ctx, *, member: discord.Member, reason):
try:
await ctx.channel.purge(limit = 1)
# await member.ban(reason=reason)
memberName = member.name
memberTag = member.discriminator
author = ctx.author.name
tag = ctx.author.discriminator
embed = discord.Embed(
title=(f"Был забанен {memberName}#{memberTag}") ,
color= 0xff0000
)
embed.set_footer(
text="| Правительство SK",
icon_url= ctx.guild.icon_url,
)
file1 = discord.File("./ImageS/user_card.png")
embed.set_image(url='attachment://user_card.png')
date = datetime.datetime.today()
embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True)
embed.add_field(name="Срок бана:", value="2 дня", inline=True) # по очереди потомучто в конце True
embed.add_field(name='\u200b', value='\u200b', inline=False)
embed.add_field(name="Причина Бана:", value=reason, inline=True)
embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/user_card.png")
neither was mine, see there would be some other option for that..
problem, my bot is having an epileptic fit, whenever a keywork is typed, the bot types out the content but then it detects it and deletes it, and then this just cycles
ik just sad...
how do I make the bot ignore itself
if bot.user: return
if message.author == bot.user
oh k thanks
lemme get my id card
how to make the role for clicking on the reaction, but give it to those who have 100 messages on the server, and those who have not typed the error message
if 'lol' or 'yes' or 'noob' or 'woah' in message.content:``` Why does this detect every message that is sent, even if it's not one of those words, even if its a number??
Non-US State or CA Province
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
what do i enter here?
non-us maybe?
ca is related to canada i think
oh ok thanks
ok done
thx
if message.content in ('aye'):``` this does not work because if a message is like "aye wassup" it wont detect it, the message has to litteraly just say "aye"
'aye' in message.content
u check if there is a apple in a basket not the other way arnd
oh yes
Is this the correct code to
- Give the user a warn
@client.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, user: discord.Member,*,reason=""):
if reason == "":
embedVar8 = discord.Embed(
title=(f"Error"),
desription=("Please specify a reason!"),
colour=(0xff0000))
await ctx.channel.send(embed=embedVar8)
else:
embedVar9 = discord.Embed(
title=('**User Warned**'),
description=(f'{user} has been warned because: {reason}'),
colour=(0xff0000))
user_id = str(user.id)
if user_id in db:
db[user_id].append(reason)
else:
db[user_id] = [reason]
await ctx.channel.send(embed=embedVar9)
- Delete the mentioned warn a user has
@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
embedVar11 = discord.Embed(
title=(f"Removed warn of {user.name}"),
description=(f"Warn {n} of {user} removed!"),
colour=(0xff0000))
if user_id in db:
db[user_id].pop(reason)
await ctx.channel.send(embed=embedVar10)
Are these code correct?? I think 2nd one is wrong
but trying to do multiple things
-_-
hah
lol
!e ```py
content = "hewoooo baka"
words = ("hey", "baka")
if any(content.contains(word) for word in words):
print("works")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
works
please help me
in should be faster
your code seems fine, unsure about your json
actually i thought of smthing better
the 2nd one is but working
wait was my method better

what method? 
^^
not really
um, no..
!e
word = 'baka'
words = ['baka', 'bakabaka']
if word in words:
print('baka')
@shrewd apex :white_check_mark: Your eval job has completed with return code 0.
baka
hmm but less to type with in and no major diff in perfomance
baka = ["e"]
if baka in message.content:```

mine dont work if baka in message.content: TypeError: 'in <string>' requires string as left operand, not list
__contains__ is a function, so it has to look it up and call it. in is keyword so its just direct call
lmao at first i just looked at the decimal points
the other way arnd...
bro it doesn't work the way i want it
!e
@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
embedVar11 = discord.Embed(
title=(f"Removed warn of {user.name}"),
description=(f"Warn {n} of {user} removed!"),
colour=(0xff0000))
if user_id in db:
db[user_id].pop(reason)
await ctx.channel.send(embed=embedVar11)
it only detects it if the message is only "e"
it wont work the way u want just coz u want it u have to code it that way smh
@topaz wraith :x: Your eval job has completed with return code 1.
001 | File "<string>", line 10
002 | await ctx.channel.send(embed=embedVar11)
003 | ^
004 | IndentationError: unindent does not match any outer indentation level
i'm just gonna do this
wont work
why are u trying to eval a discord command?
uh, idk
i wonder why didnt it raise an error for @client.command tho lmao, isnt client not defined here
sometimes i just wonder am i that bad at explaining 🥲
!e client
First the python interpreter checks for indent issues then other
how to check user has nitro or not
oh hm,that makes sense
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
you simply cant check if they have nitro or not, all you can check is if they are boosting the server or not
!e
@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
embedVar11 = discord.Embed(
title=(f"Removed warn of {user.name}"),
description=(f"Warn {n} of {user} removed!"),
colour=(0xff0000))
if user_id in db:
db[user_id].pop(reason)
await ctx.channel.send(embed=embedVar11)
@topaz wraith :x: Your eval job has completed with return code 1.
001 | File "<string>", line 10
002 | SyntaxError: 'await' outside function
lol
.
The modules won’t load to get the prefixes for the servers
so in javascript you have this thing where you can do this:
/.note./
```how is this done in python where only the taxt in bwtween the slashes is set as a not and you can still write code after it
<PublicUserFlags value=64>?
Do a # for it
i dont get it
'''thing here?'''
dict() it
im kinda sure its either js // this is a comment, or /* this is a comment */ in js , nothing like /. ./ exists
nope, not working
yep
yeah sry new to js
there is no argument for nitro
@granite parcel
Show
ah
but that will be wrong for others

sigh
what
@slate swan py if any(message.content.__contains__(baka) for baka in message.content):
dis no work
dosent this just check for whether message elements are present in message?
the problem is it just detects every single message
sent, not even the messages in baka
message.content here should be the list of blacklisted words
Hey @crisp drift apologies for the ping, but how can I set the propagate to False? I am using getLogger() rn, so I should do getLogger().propagate=False or access the basicConfig?
so message.content should be baka?
if any(message.content.__contains__(baka) for baka in ['''blacklisted words''']):
baka is the blacklisted words though
Nice, I like it when someone uses direct dunders
looks cool
alright it works thanks
makes it look out of convention kinda
sarth how long did it take for u to get the application approved
How to get the time of writing the last message from the participant and compare it, let's add 4 hours to the time of writing the message and make a check
I would love it when u do that in https://discord.gg/dpy and they criticize u for using dunders loll
get the logger object then you set its attribute to false
they criticize me for everything
Gotcha, so logger.propagate = False, right?
even if ask for 2.0 doc link in help channel says go take it playground
You need to instantiate Logger first
Yea logger = getLogger()
Yes
Thankss!
lmao
You can also do logging.StreamHandler() to add your handler @maiden fable
You deserves to go to extra hell after this ffs
?tag search <tag_to_find>
?rtfm lastest <feature> ease
i searched 2.0 once and got like a 100 tags
hmm will keep note
nice
I get the joy of being hated by most dpy regulars who have never met me 
how was ur cs exams went good?
any idea how to fix code where yesterday discord.ui buttons was working but now it says discord.ui isnt a thing?
It somehow downgraded to 1.7 overnight then
how?
ok thx
aced it, gonna get an A grade for sure
Use docker 👍
This kinda looks like java with .equals()
Being a fork maintainer has the advantage of dpy hardcore fans hating you for no good reason
what?
nice🎉
but idk what it is
eh that was from sarth i would just use an in
just pinning dep versions with pip even
🥶
This is only an issue you could have really.
do they downgrade even?
like the lib just had a mood and depreceated themselves or rolled back?
Why
How to create a thread from a member's post?
How?
len(self.client.users) work to get all the users the bot knows?
🫂
As long as u have members intent, yes
and possible to get total commands in the bot?
self.client.commands
it should be possible in 2.0 lemme check the docs
how to get creation date of my bot?
Okay, i wait
you do know how much we all hate the dpy server not to mention I sometimes do help there
self.client.created_at
ig something similar not sure
user has a created at object should work with bot too
yeah created_at
!d discord.ClientUser.created_at
property created_at```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
thanks you
np
created_atin 2.0 too?
yeah
they should make it case insensitive
I mean, it's not like I was saying good bout it
i tried to help there too but most problems were either intents or just python venv stuff
The command? Lol that's gonna ruin all the fun
atleast add a hint
I know THE BIGGEST problem that's everyone gonna face who starts with discord bots in the near future- "The bot doesn't respond to commands"
ah the process_commands as well
And a common solution-
- Enable message content intents from DDevs Portal
- Enable it in your code
That too
‘Bot’ object has no attribute ‘created_at’
Is there an event for invites?

bot.user.created_at
something like bot.user
yea
I’m in a cog
Then, its self.bot.user
’Bot’ object has no attribute ‘created’
💀
Pass it to the module. I don't really deal that much with logger so I'm not an expert with it neither
!d discord.ext.commands.Bot.user
property user```
Represents the connected client. `None` if not logged in.
@sick birch could you go over how docker works? bcs im really lost here
wrong channel bud
right channel
isnt this used for dc bots?
at 8:43 he said "Docker is good since your libraries don’t magically downgrade" in this channel so it is right
bcs its a rpely to that
its related to discord bots bcs thats why i need it
.
Ah okay thanks!
Dear. why is it throwing an error? why is he a member and gives out a reaction for one text? how to fix? help me please
@commands.has_role(982744620792426537)
@commands.command(name = "бан", aliases = ["забанить", "ban"])
async def command_clear(self, ctx, *, member: discord.Member, reason):
try:
await ctx.channel.purge(limit = 1)
# await member.ban(reason=reason)
memberName = member.name
memberTag = member.discriminator
author = ctx.author.name
tag = ctx.author.discriminator
embed = discord.Embed(
title=(f"Был забанен {memberName}#{memberTag}") ,
color= 0xff0000
)
embed.set_footer(
text="| Правительство SK",
icon_url= ctx.guild.icon_url,
)
file1 = discord.File("./ImageS/user_card.png")
embed.set_image(url='attachment://user_card.png')
date = datetime.datetime.today()
embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True)
embed.add_field(name="Срок бана:", value="2 дня", inline=True) # по очереди потомучто в конце True
embed.add_field(name='\u200b', value='\u200b', inline=False)
embed.add_field(name="Причина Бана:", value=reason, inline=True)
embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/user_card.png")
except discord.Forbidden: return
async def command_clear(self, ctx, member: discord.Member, *, reason):
Oh thanks
👍
message_redo.replace('e', '3').replace('a', '4')
await message.channel.send(message_redo)``` Can someone tell me why this wont replace the characters in the message
@commands.Cog.listener()
async def on_message(self, message):
if any(message.content.__contains__(baka) for baka in ["words"]):
if message.author.bot:
return
await message.delete()
message_redo = message.content
message_redo.replace('e', '3').replace('a', '4')
await message.channel.send(message_redo)``` (Full code)
how to test if a variable with a specific name exists
?
locals()['variablename']
what? how does that test if it exists
Can someone help me?
just do if 'variablename' in locals()
looks like u need to pip install a library
error says it all
@Bot.command(name='join', help='Tells the bot to join the voice channel')
async def join(ctx):
channel = ctx.message.author.voice.channel
await channel.connect()
!pypi anime
If it is triggered, the !join command gives such an error.
https://discordpy.readthedocs.io/en/stable/intro.html
read the "to get voice support" part
but i use Virtual Environments then I don't know which command to use.
same thing... just run this in your venv...
Can someone help?
does it send the message?
oh i think i figured it out. thnx man
Don't you need to assign it to a variable for replace @scarlet aurora
Variable = Variable.replace()
if some words r in the message
this
is it possible to make a music bot that plays songs from newgrounds.com?
thanks
you have to redefine
never heard from that website, you're asking very specific questions
Wouldn't that be against newgrounds TOS
lol okay
idk just asking if its possible before i go and check that bcs if its not possible theres no reason to check
how do i get the id of a channel by mentioning it? example:
.channel #discord-bots
bot output:
ID: 343944376055103488
You can't just rip copyrighted songs from a website and play them for people
I already got it by name, but I wanted to make by mention
ok then nvm
If you're linking them it's different but playing them requires a deal and performance royalties I think
The message.content should have the ID in it, it'll be wrapped by something you'll need to replace though
Heyy
How do I know, like how many members use my bot ( members of all the servers the bot is in )
how can I replace only the specialised word with the replacement words? ```py
@commands.Cog.listener()
async def on_message(self, message):
if any(message.content.__contains__(baka) for baka in ["word", "WORD"]):
if message.author.bot:
return
await message.delete()
messageredo = message.content
message_redo = messageredo.replace('e', '3').replace('o', '0').replace('a', '4').replace(
'i', '1').replace('E', '3').replace('O', '0').replace('A', '4').replace('I', '1')
await message.channel.send(message.author.mention + " -> " + message_redo)```
based on your question the actual thing is bot.get_all_members()
but you're looking for bot.users
use a dict, u can do this
replacements = {'a': '1', 'b': '2'}
string = 'abc'
for key, value in replacements.items():
string = string.replace(key, value)
Dear. how to make a ban for 2 days? gives an error
@commands.has_role(982744620792426537)
@commands.command(name = "бан", aliases = ["забанить", "ban"])
async def command_clear(self, ctx, member: discord.Member, *,reason, time: int):
try:
await ctx.channel.purge(limit = 1)
# await member.ban(reason=reason)
memberName = member.name
memberTag = member.discriminator
author = ctx.author.name
tag = ctx.author.discriminator
embed = discord.Embed(
title=(f"Был забанен {memberName}#{memberTag}") ,
color= 0xff0000
)
embed.set_footer(
text="| Правительство SK",
icon_url= ctx.guild.icon_url,
)
file1 = discord.File("./ImageS/user_card.png")
embed.set_image(url='attachment://user_card.png')
date = datetime.datetime.today()
embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True)
embed.add_field(name="Срок бана:", value= time, inline=True) # по очереди потомучто в конце True
embed.add_field(name='\u200b', value='\u200b', inline=False)
embed.add_field(name="Причина Бана:", value=reason, inline=True)
embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/user_card.png")
except discord.Forbidden: return
@paper sluice smthing like this? ```py
@commands.Cog.listener()
async def on_message(self, message):
if any(message.content.__contains__(baka) for baka in ["words"]):
if message.author.bot:
return
await message.delete()
messageredo = message.content
replacements = {'e': '3', 'a': '4', 'o': '0', 'i': '1'}
for key, value in replacements.items():
messageredo = messageredo.replace(key, value)
await message.channel.send(message.author.mention + " --> " + messageredo)```
it says <generator object Client.get_all_members at 0x0000014216CB8F20>
u need to iterate using a for loop
thats a list, you need to use len on it to get number of users
@slate swan
what you tryna do?
replace only the (baka) words in the message
mem = len(client.users) like this?
yes
help me pleace🥺
generator*
@slate swan ?
says "0"
do u have mod.command_clear somewhere?
just use str.replace with a proper logic? i ain't home rn so can't actually look into the src
um yeah, get_all_member returns a generator
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
I dont know. I only need to
embed.add_field(name="Срок бана:", value= time, inline=True)
released 2 days
weird u should have a command_clear or smth somewhere in yr code
How to find the last message of a member in a channel?
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
But a specific participant?
channel.history and keep looping until you get a message from that user ( message.author == ur user)
Wym
async def command_ban(self, ctx, member: discord.Member, *,reason, time: int):
fixed
Well, find not just the last message in the chat, but from a specific user
Not gonna work
move the time arg before the *
@slate swan I hate FastAPI 😔
wot makes you say that lmao
Bad error handler, bad logging
can't you customise the logging yourself?
It doesn't want to get customized 😔
Have u used the module before?
Helped thanks just a question. what does the variable "Time" represent? seconds, minutes, hours, days?
fastapi? no
logging yes
Its seconds
https://stackoverflow.com/questions/63510041/adding-python-logging-to-fastapi-endpoints-hosted-on-docker-doesnt-display-api checked this yet?
Nice then can u help me with logging in #ot1-perplexing-regexing?
im not sure if i know it the right way, all i know is logging levels and basic functions
That is what i need help with
yea that's seconds
did you make a log config dict?
Tf is that
What if you need days?
.ban @slate swan reason 2 days
idk anything about logging, sorry 😔
U need to make a TimeConverter
!d logging.config.dictConfig
logging.config.dictConfig(config)```
Takes the logging configuration from a dictionary. The contents of this dictionary are described in [Configuration dictionary schema](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema) below.
If an error is encountered during configuration, this function will raise a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError"), [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError"), [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError "AttributeError") or [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError "ImportError") with a suitably descriptive message. The following is a (possibly incomplete) list of conditions which will raise an error...
Ah, yes I tried using this but it still didnt fix my issues
sadly I don't have the JSON with me anymore since I forgot to commit to github 😅
Is disnake slow in comparison to other libraries? Especially adding reactions and stuff?
no
so basically FastAPI won't let you have ur own configs, weird
or I did it wrong?
both discord.py and it forks have the same speed
show code owo
I wanna do smth like- Remove the sys.stdout and sys.stderr stream handlers from all the loggers in my code and instead make it so that they write logs to a log file
Then maybe something is wrong with my upload speed. I'll check the program again later on 👍
This is my current code which outputs to both the file and the stdout:
root_logger = getLogger()
root_logger.addHandler(FileHandler(main_log_file))
root_logger.propagate = False
basicConfig(
stream=file,
force=True,
level=DEBUG,
style="{",
format="{asctime} - {levelname}: {message}",
)
This is inside an app.get() func, so there is a different log file for each request where file represents the log file
did you try using thr filename kwarg in basicConfig?
yup, same thing
The issue is: It is writing to the log file
But it is also writing to console
@slash.slash
@client.command
can i use both without making both separately
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
I'll suggest to not use 3rd party libraries at all.
Did you remove the first handler which is stdout initially
global k
k = None
def __init__(self, bot, k):
self.bot = bot
self.k = k```
`discord.ext.commands.errors.ExtensionFailed: Extension 'commands.suggestion' raised an error: TypeError: Suggestion.__init__() missing 1 required positional argument: 'k'`
whats wrong?
How do I do that? Using RemoveHandler?
root_logger.removeHandler(sys.stderr)
tried this?
Lemme try
root_logger.removeHandler(StreamHandler())*
logger.handlers[0] should return the stdout
Oh lemme print that
you didn't pass in an argument for k paramter
istg tensorflow takes ages to load
[<FileHandler C:\Users\HP\Desktop\Python Stuff\sesquip\logs\logs.txt (NOTSET)>] this is what root_logger.handlers returns
Get a private channel so we dont talk here
and how do I do that?
Are these the right permissions to activate the slash commands?
at last
This is a feature since a few weeks
its officially out.
I have that in some of my servers
github is fast, got pro in like 3 hrs damn i was expecting to way days just like i did for copilot xD
||Should|| ||I|| ||run|| ||!ot|| ||or|| ||!rule 7|| ||?||
try it 👀 👀
nvm
They verified my Student status in like 3-4 hours lol
they nais to kidz
Indeed lmao
4-5 hrs over
?
i applied for student
Oh
congrats ur an adult 👏 

it took 2 days for me get verified
😌 i thought it was something wrong with mine
how do they even verify btw?
they hack into school db?😎
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
🥲 sorry just a jk
Nah they just make a person see if the school is a valid one and the ID Card is valid
No verifications
oh no wonder it takes time
the guy responsible for my Id is on a lunch break probably
Or with schools having their own outlook domain.
*shes salty because shes trying to find the answer for that for years
Ours don't
mine does ig...
I got verified in 1 second because of that.
welp it doesn't
you guys sure can move to an ot channel, right?
Talk ended
hello
Hi
!d await connect
6.4. Await expression
Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.
await_expr ::= "await" primary
``` New in version 3.5.
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
TNX ❤
Dear, please tell me how to display days instead of seconds
@commands.has_role(982744620792426537)
@commands.command(name = "бан", aliases = ["забанить", "ban"])
async def command_ban(self, ctx, member: discord.Member, reason, *, time: int):
try:
await ctx.channel.purge(limit = 1)
# await member.ban(reason=reason)
memberName = member.name
memberTag = member.discriminator
author = ctx.author.name
tag = ctx.author.discriminator
embed = discord.Embed(
title=(f"Был забанен {memberName}#{memberTag}") ,
color= 0xff0000
)
embed.set_footer(
text="| Правительство SK",
icon_url= ctx.guild.icon_url,
)
file1 = discord.File("./ImageS/user_card.png")
embed.set_image(url='attachment://user_card.png')
date = datetime.datetime.today()
embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True)
embed.add_field(name="Срок бана:", value= time, inline=True) # по очереди потомучто в конце True
embed.add_field(name='\u200b', value='\u200b', inline=False)
embed.add_field(name="Причина Бана:", value=reason, inline=True)
embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/user_card.png")
except discord.Forbidden: return
U gotta make a TimeConverter, I told u
in pycord after i use a slash command and interact with a button, there is a leftover reply that says the application did not respond but i see that everything i wanted to happen after clicking the button worked. is this because of interaction.defer()? how would i fix this
Oh, where do you write it down?
!d discord.ext.commands.Converter that is a converter
class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.
This allows you to implement converters that function similar to the special cased `discord` classes.
Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
you did it right
what's the question
make an embed and send it

pretty sure you've made plenty of embeds already
and in the if you can set the embed title
or make the embed in the if
Copy paste
this is like asking how to do square roots in 12th grade
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
hyperlinks allowed in discord footers?
No
poop
there goes your plans for the evening
f
How do I specify a user limit when creating a channel?
What do you mean
Well, I'm creating a voice channel with the help of a command, how can I make it so that when using a command in this voice channel, a connection limit for 1 person is made
await guild.create_voice_channel(..., user_limit=1)
i know the title allows it
field bodies and the description
but where else
i see
I figured it out, thanks. although this thing is very difficult for me, I did it differently. via if
the title doesnt allow it, but may have a url provided as a separate parameter iirc
yeah thats what i meant
Technically doesn't allow it, but it makes the effect of being a hyperlink
Cool!
😋
That is the way most people who ain't familiar with converters go for
Well, I downloaded python a week ago.
learn python first...?
I decided to study python because js seemed difficult
They're about on the same level of difficulty
At least Python doesn't has ===
lol
'5' == 5 // True?!
Loll
I had a meme somewhere regarding some weird JS stuff
smth like 0 === [] is true but the vice versa ain't
'5' == [[5]]
Good thing I don't code in JS
yeah luckily though if you use == other JS devs are going to give you the death stare
it's almost a sin to use == nowadays
Saw it
I have this multi-line f string in my embed description```py
"""
{FIVE} Excellent {"".join(bar_form(five_stars))}
{FOUR} Very Good {"".join(bar_form(four_stars))}
{THREE} Good {"".join(bar_form(three_stars))}
{TWO} Fair {"".join(bar_form(two_stars))}
{ONE} Poor {"".join(bar_form(one_stars))}
"""
the {"".join(bar_form(five_stars))} is a list of emojis.
I'm trying to make that list of emojis appear at the same indent as each other list down. but the above code gives
what do I change?
You need special characters that look like spaces but aren't
do you have the unicode?
No but this website has a few https://qwerty.dev/whitespace/
do you know what i'm doing wrong?
i also want it to be more closer to the words, if possible
The regular whitespaces have to be replaced as well
The ones after "good" "fair" and "poor"
I think in this case you should probably try to find a workaround, semantic whitespace without a monospace font is always gonna look funky on some device, perhaps put the stars bar between the number and the text
Or dots, like a table of contents
what do you mean dots?
Like
5️⃣ Excellent ................................................................ ⬛⬛⬛⬛⬛⬛⬛⬛⬛
My bot is not online. I use heroku
it cant find the interaction
I assume you tried to react to a message the bot sent before a restart
role = await self.client.get_role(9042165867449938699355402)
await member.add_roles(role)
'Bot' object has no attribute 'get_role'
get_role is a method of guild
you can only get a role from a guild
persistent views?
Nope, you can use a member object too if the member has that role
yea I mean thats true but there isnt a direct method for it
sure you can use utils.get etc
!d disnake.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
this is discord.py
so i forgot guild?
no, just bot does not have a get_role method
you cannot do bot.get_role you get do guild.get_role though
so to get guild you can do bot.get_guild(id) OR if this is in a place where you can access the context you can do ctx.guild.get_role /message.guild.get_role or whereever this is located
I mean it overall works the same disnake and others are forks of dpy, meaning the majority of their codebase is the same as dpy
just newer features differ and branch out
So this is regarding the autocomplete feature for slash commands..
Is there a way to just fetch once from a database? like when the user starts using the command
async def autocomplete_username(self, ctx: CommandContext, user_input: str = ""):
choices = []
accounts = await api_request(method="get", request_url=get_accounts, account=ctx.author.id)
for account in accounts['accounts']:
if user_input.lower() in account['username'].lower():
choices.append(Choice(name=f"{account['username']}", value=f"{account['username']}"))
log.debug(f"Choices for autocompletion : {choices}")
await ctx.populate(choices)
So that it only run api_request() once, when the user start typing the command
im trying to make specific arguments of a command require specific roles how would i do that?
for example
!credits add * Only for admins
!credits use * Only for members
group commands be like
where you use command checks for every different group command
Can someone please answer this stack overflow question: https://stackoverflow.com/questions/72522866/issue-with-addding-roles-to-people-in-a-server-with-a-discord-bot-leveling-syste?noredirect=1#comment128115164_72522866
hm the first thing that I'll suggest it to not use json
you may use some local db like sqlite3 instead, which is actually meant for data storage purpose
reasons ^
^^ this will be your main focus, start by using an actual DB, with an async wrapper
like for example
aiosqlite is the async wrapper of sqlite
Ok so I am trying to import a file from another folder into my cog file
But it gives me this error
is tools a top level folder?
The folder I am importing into is the Cogs
Then the Tools Folder
are you running the changePrefix.py file?
oh yes you are, thats the issue
dw that won't raise an error when you run the main file 
just a sidenote: use underscore_naming instead of camelCase in python for variable and file namings
for classes it would be PascalCase
What command are you running to start your bot?
That's why
you have to run python3 main.py i believe
And what happens?
Does it do that instantly?
Or is there a delay
maybe try py main.py?
!paste Ah okay, can you paste the entirety of main.py in here?
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.
No client.run()?
🤔 strange it should at least say it's ready
Can you try printing something before you do the client = commands.Bot(...) stuff?
Am I able to make a bot repeat a command every hour?
You'd be interested in the discord.ext.tasks extension then
Well I need the Tools folder to be able to find them
Oh something's really wrong then
Or the bot's prefix can't be found
@frozen patio read this
oh my, that's not right at all
your problem is with relative imports
I doubt it's nextcord
Since it can't even run a print statement as the first line
Just for testing, can you remove everything else and only have the print statement? so your entire file should just be one line with the print statement
that way we can narrow it down to a nexcord issue or python issue
It wouldn't even run that file with a print?
Can you try command prompt?
Use cd to navigate to the right folder
vscode has a python extension for running code, try using it to run the code maybe?
@slate swan Are you sure you're running the file your editing?
Where can I show off my projects
Did you save your file?
What type of projects?
Games
#game-development I suppose.. (if it's made in python)
I think
I don't really know
What does the prompt say?
I mean, what does it say to the left of your cursor? The stuff before the >
That should tell you what your cwd is
You can code on any computer really
I can code just fine on my macbook pro
Though usually I'm on linux on my desktop
Wdym access it?
idk how to get to it
its the terminal~
Node should have a specialized mac download
i downloaded it
Can you try using command prompt?
that's node
🤔
yeah
https://docs.npmjs.com/downloading-and-installing-node-js-and-npm#os-x-or-windows-node-installers this page might help you
Did you install the macOS installer or macOS binary?
@slate swan
😩 just use brew to install node&npm
brew ⁉️
i clicked on that and it installed it without saying which one
Why are you even asking about node in a python server?
And did you double click the .pkg?
cause im trying to use it for the bots
then where should i go to get help
@median widget if you want we can move to #ot2-never-nester’s-nightmare
hey can any1 help me with a problem I'm tryna figure out with my crypto bot
so basically I have a database off a bunch of crypto currencys and there price [id], [current-price]
and I want to make it so that when someone does $crypto-name it responds with the price
Doesn't sound like a problem to me?
but right now it just responds when someone writes the cryptos name because I check the message by saying if message.content.lower() in db.keys():
Responds with..?
and I don't understand how to change it so it responds when it starts with a $ while fetching it
the price
‘‘‘if message.content.lower() in db.keys():
await message.channel.send(f'The current price of {message.content.lower()} is ${getCryptoPrices(message.content.lower())}')’’’
Make it a command instead of using on_message
bot = Bot(command_prefix='$')
@bot.command(name='crypto-name')
async def crypto_name(ctx, name, ...) -> ...:
... # get the cc and get its price
it says bot is undefined
How to ignore the commands when the command usage is exceeded like the command is *bot but it replies when someone writes after it
!d discord.ext.commands.Bot import it.. or import commands from discord.ext
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
.
ignore_extra=False in @command()
it will raise a commands.TooManyArguments error if user provides extra arguments
Everywhere?
It will be too long i have more than 280 cmds
im not sure if there's a shortcut to do it everywhere automatcially, but you can just
you can just ctrl+f command( and replace it with command(ignore_extra=False,
for command in client.commands:
command.ignore_extra = False```
This would work on ready func?
Can someone help me in #help-carrot please.
yes that should work too
gg
Please.
U ugly
There's no need to say that.
its just replit being replit
i would recreate the pyproject.toml by my own but you should do that only when you are aware how poetry works
Hi
create a new repl then :)
this might be an issue with replit's outdated python version too.
I have basically no clue what I'm doing... I'd like to code a discord bot and I have experience in c#, c++, python, and a little bit in js and java.
I've made one discord bot in replit following a tutorial but I still don't know what I'm doing and I'd like to build a bot to run locally on my own server. Are there any good resources out there that I should start by checking out?
hey, do you have basic knowledge about asyncio, classes, functions, and flow control?
!resources you can actually look into these first, since already have a hold on cpp,i believe you are already aware of how objects works?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
yeah, I think so
Code
e.description = f"""
Current Community Rating:
{overall_stars}
{avg_rating} out of 5 stars
{sum(single_reaction.count -1 for single_reaction in all_reactions)} ratings
5 stars
{"".join(bar_form(five_stars))}
4 stars
{"".join(bar_form(four_stars))}
3 stars
{"".join(bar_form(three_stars))}
2 stars
{"".join(bar_form(two_stars))}
1 star
{"".join(bar_form(one_stars))}
"""
await message.edit(embed=e)
the output of this on pc is like this
but on mobile it's like this
why the indent on mobile?
Cuz
Screen smol
And discord mobile is weird sometimes. It's probably because of screen size why that happens udk
Indeed
does discord have a bar?
It will look different on an iPad/Tablet
Bar?
how can you get that bar that @def init(self,Snoggy) uses
so nothing I can do?
woops
Double underscore in your name
i mean @spring flax
Ahh
That's an emoji
i made it with emojis
use textwrap.dedent
sure it'll work right?
!e
import textwrap
a = """
hello
world
"""
b = textwrap.dedent(a)
print(a)
print(b)
No that's just discord mobile issue
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | hello
003 | world
004 |
005 |
006 | hello
007 | world
Doubt that would affect how it's rendered on mobile as embeds have a fixed max width
i'll just fwiw
they are different ones, the first one has emojis second one doesn't
oh perfect thank you Ryuga that worked
Is it possible to have slash commands which are only visible to a few people?
Yes
With the discord slash command permission found in server settings > intergrations
Thanks!
By the way, any idea how to make an error handler for a specific slash or user command?
@command_name.error
Oh okay, I thought it only worked with the prefixed commands only. Thanks Asher :)
with pycord
rnames = []
for role in player.roles:
rnames.append(role.name)
trole = discord.utils.get(ctx.guild.roles, name=team)
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
await player.remove_roles(['Tokyo Fart Sniffers', 'Baltimore Bughas'])
await player.add_roles(trole)
elif rnames not in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
await player.add_roles(trole)
is this format for removing roles in list wrong? i tried my command but it doesn't remove the users roles
remove_roles takes a discord.Role object, not a list
ah so i'd have to put it in a for loop then
You can unpack the list of Role objects to add_roles/remove_roles
Role``*Role*Role
Ahh.
Should i make ghost ping logs or message delete logs are enough?? :?
hey, when i do from discord.ext import menus, it gives me this error
i tried pip install git+https://github.com/Rapptz/discord-ext-menus.git, but it had no effect
what do i do
how do i install git+https://github.com/Rapptz/discord-ext-menus.git in dpy.ext location
python -m pip install -U git+https://github.com/Rapptz/discord-ext-menus
-U tag means upgrade so ur modifying the already installed one
What makes sense since it's a dpy extension
What version of dpy are you running? 1.7.3 or 2.0?
2.0
i am using pycharm venv, do i need to do .\venv\scripts\python.exe -m pip install git+https://github.com/Rapptz/discord-ext-menus.git?
ya
a venv is like another installation of python, so u have to install it there as well
okay that worked
I just use the build-in package manager I don't really bother with the console.
thanks a lot you guys
If you click on Python Packages next to terminal and then add package and add package as version control you can insert git urls.
As for pypi packages it has a build in search in there too.
thanks a lot!
i am using interaction.send_modal
but i get an error that modal has no attribute to dict.
Any idea on how to fix it ?
how to find if a member has any badge in their profile ?
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
@unkempt canyon u suck >:)
Could not convert "user_or_message" into Member, User, or Message.
Message "suck" not found.
!user [user_or_message]
Can also use: member_info, member, u, user_info
Returns info about a user.
ahahahaaaaaaaaaaaa
and he starts trashtalking as well hahaaaaaaaaaaaa
what
you could stop you know
Ashley today i will start learning hikari
code and traceback?
Could you provide more info? Code/tb
what's to learn in that 😔
Save the time and code more in dpy.
its easy though good luck
dpy, ew
It's weirdness
CommandTree
Wow pulling that card smh
what I would expect something from a third party lib
I mean, who would have thought to have shat that much
You got a point tough the commandtree is just very bad atm.
xD, and the manual sync is a big headache
Ignoring exception in command bug_report:
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 126, in wrapped
ret = await coro(arg)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 856, in _invoke
await self.callback(ctx, **kwargs)
File "e:\Python PRojects\Top War Bot\Top war bot\Cogs\Bug_Report.py", line 34, in bug_report
await ctx.send_modal(modal=modal)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 899, in send_modal
payload = modal.to_dict()
AttributeError: 'Modal' object has no attribute 'to_dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 357, in invoke
await injected(ctx)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Modal' object has no attribute 'to_dict'
if they were worried about uniqueness, they sure did a good job of having their users have to do more work
I'm going to work on that eventually if they decide to never add it.
CODE:
modal = Modal(
custom_id="Bug Report",
title="Bug Report",
components=[
TextInput(
style=TextStyleType.SHORT,
custom_id="What kind of Bug",
label="What kind of bug ?",
placeholder="Purchase Related, In-game Related etc.",
required=True
),
TextInput(
style=TextStyleType.SHORT,
custom_id="Server Related ?",
label="Please specify which server in case of a server-specific bug.",
placeholder="Leave blank if it is not.",
required=False
)
]
)
await ctx.send_modal(modal)
What lib
yeah, would be better if it could be done like
CommandTree(client_ins, auto_sync=True)
Bot.tree.auto_sync = True
something like that could help
Will be better but won't fix all issues atm.
ye
https://github.com/Rapptz/discord.py/blob/master/examples/modal.py
There is an example
Idk try seeing if u r doing the same thing
yep, dunno why they would want users to sync the commands on their own
gonna annoy people in the dpy server now
Yeah I suggest using this method, looks better as well.
Automatic syncing isn't necessary a majority of the time and it's a waste of API calls
hm yeah figured that out but still
hello
👋
can bot use commands other bots ?
await ctx.send("!help")
and other bots get respond?
No that's not possible.
;-;
sad ashley noises
its fine
assumes gender
and I saw that, you didn't have to delete it, I wasn't gonna bite you or anything
😐
thanks and .. sorry
sorry for what, told you its okay


💀 msg deleted
!ot 💀
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
Tbh, in this channel.... no one cares anymore
This channel is for telling people to learn python for half of the time and the other half for us talkin' about people who want to code a bot in d.py without knowing python
how do i make timeout cmd in discord.py
agreed
!d discord.ext.commands.cooldown
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
ye that
Oh wait does he means timeout a member or command cooldown? xD
after a long long time, i figured that it wasnt updated. Python 3.11 was messing with it due to a bug since its in beta, i think. So, i had to go back to 3.10.5 and reinstall, now its fixed.
the new timeout feature
or is it even new now
well now it is pretty old
thing get old really fast
but yeah it's the newest member moderation option
how do i disable buttons on timeout
I still have no idea how to use it LMAO
imma just try to do random stuff and hope it works
do i have to import anything
from datetime import timedelta
async def timeoutm(ctx, member: discord.Member , time : int):
try:
a = datetime.timedelta(hour=time)
await member.timeout(a)
except:
pass
u can change the timedelta time according to you
mute and timeout is basically same right?
no
i thought timeout came out to replace mute
naww
oh
in mute bot gives a role to the person which doesnt have permissions to msg or not see the channel
and in timout
the discord gives u a feature that u can use instead of mute
Is someone being a menace in your server? Introducing server Time Out!
This feature enables server moderators and admins to temporarily prevent a user from interacting in a server.
What does that ...
anyone knows how can i disable buttons :/
subclassing view?
after timeout
Nice
yeah
That's the crux, I agree
use the on_timeout function/event idk what its called
class MyMenuPages(ui.View, menus.MenuPages):
def __init__(self, source, *, delete_message_after=False):
super().__init__(timeout=60)
self._source = source
self.current_page = 0
self.ctx = None
self.message = None
self.delete_message_after = delete_message_after```
!d discord.ui.View.on_timeout
await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when a view’s timeout elapses without being explicitly stopped.
class MyMenuPages(ui.View, menus.MenuPages):
def __init__(self, source, *, delete_message_after=False):
super().__init__(timeout=60)
self._source = source
self.current_page = 0
self.ctx = None
self.message = None
self.delete_message_after = delete_message_after
async def on_timeout(self):
for button in self.children:
button.disabled = True
this shoudl work
here my menu timeout is 60, when clicked after 60 secs, it says interaction failed
ohhhh thanks a lot
uhm it should be an async def lol
ya
disable=True
nvm me
not working @paper sluice@shrewd apex
oh want, where do i await it
ok nvm got it
i will go try rq
okay that aint working
How to add multiple emojis mentioned?
@hot plaza
?
@hot plaza hi i am learning python
could u help me in make a discord bot mute command
Show the code bro
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.
code?
oh k
wait
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member):
guild = ctx.guild
Muted = discord.utils.get(ctx.guild.roles, name="Muted")
perms = discord.Permissions(send_messages=False,connect=False,read_message_history=True)
if Muted not in guild.roles:
await guild.create_role(name="Muted")
await member.add_roles(Muted)
em1=discord.Embed(title="Sucsessfully Muted",description=f"{member.mention} Has been Breaking the Rules",colour=discord.Colour.random())
await ctx.send(embed=em1)```
I wanted a rough example my code works fine though for single
show us your code for the single and then we might be able to help
Alr
any error?
@hot plaza#discord-bots message
@latent yarrow you might benefit from following a tutorial on youtube
whats the error then
like this: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
Full traceback?
No
@hot plaza is this clear
i dont believe that error is in any way related to your mute command
Don't recommend that
its probably better than what they are trying by themselv
it is

send them the docs then, i bet you that it will confuse them even more
@latent yarrow , can you send full traceback
Reading the docs is a key step to being a developer
it's the only step 
better, it's the first
Indeed
the second one is understanding users docs
where and how do i await
async def on_timeout(self):
for button in self.children:
button.disabled = True```
You edit the message's view
i want my buttons to be disabled on timeout
whats the syntax for it
I believe you have a message attribute in your view class
view.edit?
!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`.
@hot plaza
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
the user is still learning python, i dont think referring them to discord.py docs will benefit them as much. i dont they understand the concept of a mute command either
Then learn python first, that'll definitely benifit them
Discord.py and similar libraries aren't beginner friendly.
They now prefer learning by mistakes*
look i do it this way
menu = MyMenuPages(formatter, delete_message_after=True)
await menu.start(self.context)```
i start start the menu this way
yea holup
async def start(self, ctx, *, channel=None, wait=False):
await self._source._prepare_once()
self.ctx = ctx
self.message = await self.send_initial_message(ctx, ctx.channel)```
Yeah you can access the message using self.message
In on_timeout, await self.message.edit(view=self)
cool! ty
any reason this dosent work?
view = View(timeout=5)
async def disabled(self):
for button in self.children:
button.disabled = True
await self.message.edit(view=self)
view.on_timeout = disabled
Weird
i tried the same thing in a button callback and it worked
Should have worked
@hot plaza : Traceback (most recent call last): File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
this is my error
post the code
wait
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member):
guild = ctx.guild
Muted = discord.utils.get(ctx.guild.roles, name="Muted")
perms = discord.Permissions(send_messages=False,connect=False,read_message_history=True)
if Muted not in guild.roles:
await guild.create_role(name="Muted")
await member.add_roles(Muted)
em1=discord.Embed(title="Sucsessfully Muted",description=f"{member.mention} Has been Breaking the Rules",colour=discord.Colour.random())
await ctx.send(embed=em1)```
here is it
@alpine cove
the code's here
@hot plaza
Same.
commands.has_permission may be the problem
would make sense if the method calls .id
od discord.utils.get
ok i will try
Wever, do you know how to change the "This interaction has failed" to something else? Kinda like an error handler for slash command with an ephemeral but with red coloured warning.
it seems the buttons are being disabled but message in not edited
Nice I almost reported this msg of yours
?
Discord Mobile being a bitch
ouf
Are you sure View has a message attribute
Yes
view = View(timeout=5)
async def disable(self):
for item in self.children: item.disabled = True
await self.message.edit(view=self)
view.on_timeout = disable
thats still ok i can manage even if it dosent but the disable function dosent run at all
View doesn't have message attribute dude
i added a print under the disable function and got nothing
thats alright but the function is not running in the first place
How can you tell
@alpine covenot working
i added print nothing printed heck i even did self.somegarbledshit and still no error
Do you send the view actually
Timeout counts since the message with view was sent iirc
yeah i did
Does it have any components
two buttons
And the buttons display correctly right?
yes
buttons work everything works except the on timeout even when i disable the view in the button callback it works
just delete the message on timeout, why disable buttons
His function doesn't even get called for some reason
yeah but the problem is it dosent get called at all
subclass like exe said
Subclass the view and try to define it there
