#discord-bots
1 messages · Page 262 of 1
there is a way to build your own type hint method if that what u want
any help?
can i see the code?
if u are using client.start(),
In the discord.py docs, it only allows token and reconnect as an argument
await start(token, *, reconnect=True)
This function is a coroutine.
A shorthand coroutine for login() + connect().
Parameters
token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.
reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
Raises
TypeError – An unexpected keyword argument was received.
Are you trying to selfbot
The bot argument was removed a long time ago
/voice verify
u need help w code?
!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.
x == y Checks if two embeds are equal.
New in version 2.0...
!e
code
my code here is not being executed
my lord the indentation
ok
like this?
my god the if statement indentation
everything
ahhahaha
whats wrong with it?
just reformat your thing and get consistent indentation, then come back
and all those empty lines, pointless
u only need one line indentation dont need 4 line of indentation
there is that better?
hahahahah check again
all those indentation just need 1
look for all the indetation
one tab?
ok
this better?
good job but the rest can work abit more too llike those functions and pass statement also but it fine so what the problem>?
btw rule of programming eb consistent
anyways so what the problem u facing?
the code I was indenting doesnt work
nothing happens
can i see the above code?
!paste
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.
https://paste.pythondiscord.com/sulelomuja @silk wasp
could u send me the try except also
More inconsistent than that is hard
wdym
its there
no mwait im not blind i meant the
line 748
u only sent until line 744
you want whole on_message?
yes
Btw you need to make sure things are consistent in programming if not things will fall apart
Unnecessarily parenthesis in if (message.author.bot), remove that
Unnecessary pass statement you dont really needed
Improper try-except block
your try-except block is place wrongly, It should wrap around the specific code that might raise an exception.
In your case, it should wrap around the code inside theif profanity.contains_profanity(message.content):condition.
@slate swan can i fix his code for him? ahahahah
no but It needs to check if the guild id is in r (r=db) and then check for bad words
If it's worth the hassle
yes please
To be fair before fixing anything should fix indentation
i see the indent and it an indent error
Because every indentation line different than the previous
this:
try:
if f'2 {message.guild.id}' not in r:
pass
else:
if profanity.contains_profanity(message.content):
await message.delete()
embed = discord.Embed(title="No bad words please")
embed.set_footer(text="Censored by profanity_filter")
await message.channel.send(f"{message.author.mention}", embed=embed)
except:
pass
is not same indent as this:
if message.author.id == client.user.id:
return
global author_msg_counts
author_id = message.author.id
# Get current epoch time in milliseconds
curr_time = datetime.datetime.now().timestamp() * 1000
# Make empty list for author id, if it does not exist
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
# Append the time of this message to the users list of message times
author_msg_times[author_id].append(curr_time)
# Find the beginning of our time window.
expr_time = curr_time - time_window_milliseconds
# Find message times which occurred before the start of our window
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
# Remove all the expired messages times from our list
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
# ^ note: we probably need to use a mutex here. Multiple threads
# might be trying to update this at the same time. Not sure though.
if len(author_msg_times[author_id]) == max_msg_per_window:
try:
+1
minutes = r.get(f"1 {str(message.guild.id)}")
min = int(minutes.decode("utf-8"))
if f'1 {message.guild.id}' not in r:
pass
else:
duration = datetime.timedelta(minutes=min)
await message.author.timeout(duration)
embed = discord.Embed(title="User muted", description=f" {message.author.mention} has been muted", color=discord.Color.blue())
embed.add_field(name = "Reason",value = "spamming")
embed.add_field(name = "Mute duration",value = f"{min} minutes")
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"log {str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)
except KeyError:
pass
And then leads to some stuff like that
it not in the same indent
yes but if it is then it will think its connected with that
But I mean that's what happens when people don't learn python
Probably a mix between self-made and pasted code
can i just end this hell ahahaha?
And the pasted code uses proper indentation like the second code block above
dam
python bot ask me paste in in pastebin zzz
wait not python bot thought i was advertising nooooo
nooooooooo whyyy anyways
What I specifically love are these 6 useless empty lines
Nevermind, they have some spaces/tabs
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.
@formal basin https://paste.pythondiscord.com/afahabeyor
ok.
fixed code.-.
for ur indent\
And also seeing that makes the code already 10 times worse than it can ever be
this should be on top of the function tbh
but then eh
global shouldn't be used at all
true true
Especially if the variable is never used afterwards
tf
Is there really no other way of making 2x2 fields without making this ugly empty field using \u200b?
nope
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
just pass inline
this will make it one per row
On second field
thats not how inline works
when inline is True then this field will be the only one on this row
ah yeah
using inline you can create one column
without you can create 3 columns
and here comes problem how to make 2
blud really thinks that he can ask for changes to the discord api dev team
so what should I learn for database shits in bot
depends what database you want to use
Can anyone recommend a discord bot thats free and will remove anyone that hasn't posted in a server for 30 days?
make ur own
i dont think there are discord bots that do that stuff but you can code your own
Yeah, tried and failed that. It pretty much started kicking everyone, will take better look at code later then cheers
lmao rip
hmm, just thinking, for that you will need to read the whole 30days history on server, or there is another way?
on_message and a db
What about days before
With that your bot will need to exist on server these 30 days
if u want to start from rn else yeah read from history
Iterate through every channel and see if a member has a message timestamp within 30 days but if not, kick.
for each member
like?
No just have events you want to check for
And then if someone didnt occur in any event for 30days
Boom gone
.
Well then you gotta have it running for 30days before it starts working
also a quick question, does ```py
bot.fetch_user(id)
its awaitable its all i know
It should

If it was fetch_member, then not
ok
ohhh
MySQL postrgesql, mongodb, Redis and many more
If you are new to this should go with MySQL or mongodb
database.json ⚔️

alright
In js you can at least import from json file
in js
"2" + 2 - "2"
= 20
I know
could I make list like this:
list2 = ["test", f"1{str(list)}2"]
so like 1t2 is in list2
or 1a2
Not relevant to the channel's topic
Hi I made a discord py code for an Image generator it generates using /imagine and generates 6 photos under 3 seconds it gives high quality photos with so much more I am making more commands is the bot good
are u generating images using ur own ai model or some api that'll be the judge 👀
Anyone can do that 
from PIL import Image
from timeit import default_timer
start = default_timer()
for img_id in range(6):
image = Image.new(size=(4000, 4000), mode="L")
image.save(f"{img_id}.png", optimize=True)
print(default_timer() - start)
Can you do it with high graphics from Nvidia
except commands.ChannelNotFound:
await ctx.send('Please mention a valid channel to lock.')
why does this dont work
you should send your code
and try to understand what you copied / coded
i didnt copy anything
async def lock(self, ctx, channel: discord.TextChannel, duration: converter = None, *, reason = "Not Specified"):
description = f"**Locked:** <#{channel.id}>\n**Locked by:** {ctx.author.mention}\n**Reason:** {reason}"
embed = discord.Embed(title = "Channel Locked Successfully!", description = description, colour = colour)
guild = ctx.guild
everyone_role = guild.default_role
try:
if channel.overwrites_for(everyone_role).send_messages is True:
await channel.set_permissions(everyone_role, send_messages = False)
await ctx.send(embed = embed)
if duration == True:
await asyncio.sleep(duration)
await channel.set_permissions(everyone_role, send_messages = True)
await ctx.send('Channel has been unlocked.')
else:
await ctx.send('The given channel is already locked.')
except commands.ChannelNotFound:
await ctx.send('Please mention a valid channel to lock.')
Do you really don't see anything wrong
The bot is trying to convert the channel argument before calling the command callback, so your try-except cannot catch it
i made the bot print error in global handler so that it would be easy for me to develop it
That's even worse
It's hard to get a sense of where an error occurred if you can't see the traceback
i have added those things
nvm
it wasnt in ur code so uk
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
@winter token try commands.BadArgument instead
ok
why my converter is working only when i give 1s as input
code here
total = 0
duration_pattern = r"(\d+)([dhms])"
duration_values = re.findall(duration_pattern, duration)
for value, unit in duration_values:
value = int(value)
if unit == "d":
total += value * 86400
elif unit == "h":
total += value * 3600
elif unit == "m":
total += value * 60
elif unit == "s":
total += value
return total
``` converter
nope didnt work either
!pypi durations-nlp
!pypi time-str
there are libs for stuff like this
oh damn didnt know, I will study abt them later
@client.event
async def on_member_update(before, after):
if f'2 {after.guild.id}' not in r:
return
if after.id == client.user.id:
return
``` ive got this code and it is a bad word filter for nicknames but once it changes the nickname it loops it
anyways u know the reason for that error?
thats not how u make a converter
so I tried this if after.id == client.user.id: return but still looping
!d discord.ext.commands.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.11)").
u inherit from this class
i have it as function
yeah dosent work that way
wdym looping?
oh so need to inherit for that to work?
when someone changes nickname the event triggers then bot changes it again then the event may trigger again that might be a case
yes
after.id is id of user whose name was changed iirc
print and check
yeah I think your right what can I do. what I think I can do is ```py
if after.nick == "the name that is given after change":
pass
else:
@client.event
async def on_member_update(before, after):
if f'2 {after.guild.id}' not in r:
return
if after.id == client.user.id:
return
if after.nick == "Bad word name":
pass
else:
badword = f"{profanity}"
if any (word in after.nick for word in badword):
new_nickname = "Bad word name"
await after.edit(nick=new_nickname)
log = r.get(f"log {str(after.guild.id)}")
embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
embed.add_field(name="Reason", value="contained bad words")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 72, in on_member_update
if any (word in after.nick for word in badword):
UnboundLocalError: local variable 'badword' referenced before assignment```
badword = f"{profanity}"
if any (word in message.content.lower() for word in badword):
await message.delete()
embed = discord.Embed(title="No bad words please", description=None)
embed.set_footer(text="Censored by better_profanity")
log = r.get(f"log {str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
embed.add_field(name="Reason", value="contained bad words")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
``` I have this code for an on_message event for anti swear {profanity} is better_profanity and if someone types anything it gets deleted
why is it deleteing any word or letter typed
Because you are iterating over string badword characters
!e
badword = "something"
print([word for word in badword])
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
And checking if any characters from this word are in the message
can u send me 1 example? didnt get in stack overflow
oh
class CustomConverter(commands.Converter):
async def convert(self, ctx: commands.Context, argument: str):
return ur_data
{context.guild.region} Can't find any documentation relating to this, has this been removed/changed?
its interaction if slash command
For a serverinfo command.
what do i do?
Not necessary for the most basic converter, aka their case
why not i often use a duration converter
Fix your code 
My point with the message above was that yes, it is
No need to over-engineer, especially for their use case where you just care about the argument and context is pointless
how do I make it not split the letters up
Make some sequence of words, not a single word.
Or if it is a single word, just check for it, without loops
i tried profanity.split
profanity is a package
for word in badword iterates through badword with its letters being the values.
eh ur preference ig its not that simple for a duration converter u need to handle edge cases like errors and bad spam input as well
there lots of words in it
plus i reuse mine in a bunch of places so subclassing is better
how can i make it the words?
If their converter works (at least in some cases according to messages), no point in telling them it's wrong and not the way to do it, but rather fix the issue they have with their actual converter
and not the letters
I believe it's removed.
there is Guild.preferred_locale, that's what you want maybe
!e
badword = "something"
print([word for word in badword])
badword = ["something"]
print([word for word in badword])
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
002 | ['something']
ok
basics of python
making bots randomly >>> normally learning language
Why bother learning if you can ask here 

wont custom converters work if i typehint the converter function ?
!paste
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.
Exception has occurred: AttributeError
partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import)
i can't find anything on google how do i solve this?
did you name your file discord.py?
im so fucking stupid i didn't notice my bad 😭
yeah you cant name files like module names cause they will stop working
now you know 👍
i know and i didn't even realize what i did until you mentioned it
i just checked it omg im dumb
well thanks
👍
async def profile(interaction,member: discord.Member):
user = interaction.member```
With this, when someone is using the command, in the embed I am getting the user who is using the command, and the username of the person someone is wanting to see. Can someone tell me how to add that? Where the username in the embed is shown of the person who is being mentioned
the person being mentined: {member} the person using this command {interaction.user}
hmm
Also what’s interaction.member??
Cuz iirc it’s interaction.user for the person using slash command and member for the selected member
yes this is correct
!d discord.Interaction.user
The user or member that sent the interaction.
Ye thought so
async def profile(interaction,member: discord.Member):
user = interaction.user```
this was the code, sorry, I was just trying to understand when doing that
so here {member} is the person getting mentioned and {user} is the person using the command
user is the person who invoked the command while member is the person specified in the command param
Ohh, how do I invoke that tho? getting the information of the member?
what type of info?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
here you have all attributes and methods it has
the names are self explainatory
if not there is description as well
Like when the user uses the slash command, gives a members name, then the username of the member is shown and ID, that's what I want rn
okay, ill look into it, hmm
go to the docs i linked read the attributes it has and you should already know what to use to get member name
the user that used the command is interaction.user the members name is just member and the member.id
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
Dumb question but
Can i replace this
def blacklist_check():
def predicate(ctx):
with open("blacklist.json") as f:
data = json.load(f)
if str(ctx.author.id) in data["ids"]:
return False
return True
return commands.check(predicate)
With this
def blacklist_check(ctx):
with open("blacklist.json") as f:
data = json.load(f)
if str(ctx.author.id) in data["ids"]:
return False
return True
To use like
@bot.command()
@blacklist_check()
async def check(ctx):
no if you do so you will need to change the decorator to @commands.check(blacklist_check)
thats why you return it already as commands.check so you dont need to do that
Ohhh
you need to have Member class object not a Member class
well discord bot isnt a good project for a beginner you need to know basics and maybe some more of python to know what you are doing
you need to gather Member object and use this method on it

how is is supposed to know what member to give/remove roles
hello
: D
async def say(interaction, user: discord.Member, ......)
why steal avatar
Looks cool
impersonating

and what is the converter
ok its below
does it even work when you annotate it as function?
did you try printing what it outputs?
I checked, his converter works fine
wdym by works? what it doesn't do in other cases? what do you get?
i am lazy to run the whole code
Ah well i see
Your duration is an integer
Why are you comparing it with True...
I’m very new to python but I want to create a discord bot where should I start
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
make sure u know oop and async programming if u do congrats open discord.py docs and the github repo which has examples and start away if u dont know the basics i would suggest to get familiar with it i will recommend corey schafer for yt guys and for books we have automation of boring stuff and bytes of python in resources which down linked above ^^
ctx.guild.icon_url doesn't work?
embed.add_field(
name="OSINT", value=" ⤷ Open-Source-Intelligence", inline=False
)```
The two spaces infront of the arrow ` ⤷` get deleted in the actual embed
Try ** **
Same issue.
Hi guys
Try
space = ' '
value=f"{space}YOUR CONTENT"
```@coarse geyser
Why the fuck would that work but not me putting a space.
You always learn new things by experiments
I used stable diffusion to generate images on discord. But my problem is that when one image is generating and someone else uses the command, my bot responds with „this application did not respond“. I also made like a queue so it adds the user who wants to generate an image to a queue and then generates the images. So why does it not respond?
You need to respond to interactions within 3 seconds
I know
If you can't, then defer the response and you can then respond within 15 minutes
But It adds the user to the queue and responds directly
Most likely not, Discord doesn't lie
Then generates images for all users in the queue in a loop
It works when a user enters the command
But someone else has to wait until the first image is generated
Even though that is in the loop and not the command
Well well
Seems like you didn't try
@slate swan
each white space character in discord message gets suppressed to only one space
if you really want bigger space before this arrow you need to use some sort of invisible character
nah you have to put anything you want in ' ', like a variable
Hey, I just wanted to say I successfully migrated my Replit bot to a DigitalOcean VPS after receiving advice to do so on this server a week ago. So thank you to those who showed me the way, it wasn't easy but I finally made it 🙂
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
docs are here for a reason check what attributes it has
async def lock(self, ctx : commands.Context,
channel : Optional[Union[discord.TextChannel, discord.VoiceChannel, discord.CategoryChannel, discord.StageChannel, discord.ForumChannel]],
duration : Optional[TimeConverter]):
print(duration)```
Hi , anyone know why I'm getting discord.Message? ( The return type of TimeConverter is int | None)
what is the definition of TimeConverter
It's subclass of commands.Converter
yeah but what is the definition
It's supposed to return int or none but
give code
class TimeConverter(commands.Converter):
def __init__(self, * , min : int = None, max : int = None):
self.min = min
self.max = max
async def convert(self, ctx : commands.Context, arg : str) -> int:
try:
time_ls : list = []
time_str : str = ''
for i in arg:
try:
int(i)
time_str += i
except ValueError:
time_ls.append(i)
try:
time_ls.append(int(time_str))
except:
return await ctx.send(":no: The provided time is invalid", delete_after = 15)
time_mapping : dict = {
"w" : 604800,
"d" : 86400,
"h" : 3600,
"m" : 60,
"s" : 1
}
new_time = time_ls[1]
unit = time_ls[0]
time = time_mapping[unit] * new_time
if self.max or self.min:
if time > self.max:
return await ctx.send(f"invalid time, maximum time is {self.max} seconds.")
if time < self.min:
return await ctx.send(f"invalid time, minimum time is {self.min} seconds.")
return time
except Exception:
await ctx.send(f'{unit} is not valid time unit')
return```
hey
anyone know why cooldown command isnt working on the latest version of discord.py
@commands.cooldown(1, 10, commands.BucketType.user) is the current code i added
how do you pass the min and max varriables i dont think Converters have the constructor
and you said it returns Message
arg : TimeConverter(min, max)
well you are doing return await ctx.send
Smart
thats why you get Message
. Duration
yes it is optional
Let me test first
what do you mean by isnt working
no errors or anything just wont cooldown
Ok so
im looking at the docs rn, tryna figure it out
Didn't work
from discord.ext import commands
class TimeConverter(commands.Converter):
def __init__(self, * , min : int = None, max : int = None):
self.min = min
self.max = max
async def convert(self, ctx : commands.Context, arg : str) -> int:
try:
time_ls : list = []
time_str : str = ''
for i in arg:
try:
int(i)
time_str += i
except ValueError:
time_ls.append(i)
try:
time_ls.append(int(time_str))
except:
await ctx.send(":no: The provided time is invalid", delete_after = 15)
return
time_mapping : dict = {
"w" : 604800,
"d" : 86400,
"h" : 3600,
"m" : 60,
"s" : 1
}
new_time = time_ls[1]
unit = time_ls[0]
time = time_mapping[unit] * new_time
if self.max or self.min:
if time > self.max:
await ctx.send(f"invalid time, maximum time is {self.max} seconds.")
return
if time < self.min:
await ctx.send(f"invalid time, minimum time is {self.min} seconds.")
return
return time
except Exception:
await ctx.send(f'{unit} is not valid time unit')
return```
Now return type should be just int or None right?
But still discord.Message somehow
is everyone making a converter today 👀
progress
!pypi time-str or use durations-nlp there are libraries for this already
also instead pf ctx.send why not raise some error and handle it at once in the error handler
Oh, thanks
I'm lazy lol
no ur doing more hard work that way
Not that much difference
all u need is raise commands.BadArgument("Invalid Time") as long as u have a decent error handler u dont need any of those if statements
Just writing ctx.send * 4 then usual lol
Thanks, will try it
lets write a gist for these features maybe a comprehensive guide seems like a good project 👀
wanna try it out?
you mean like odd features of the discord.py?
like converters and stuff
we can include modals paginators and all that stuff
a comprehensive guide ig?
all features with examples
Bro converters are really useful
best practices i suppose
i know but you are like 4th person who asks about them
as well as making handy components
and im here for a long time
Lol
down is like master oogway been here for a loooong time 👀
change pfp when? oogway way cooler than current pfp turtle guy
turtle is my symbol now
if we knew all features.. 😄
we gonna read source 
lets make it our mission
hmm think I'll start writing one from tomorrow
!d discord.Attachment
im in
how can I get the text contained in an inputted discord.Attachment
aight cool a repo or a gist i think we can have a repo examples and a gist explaining
you mean someone sent a .txt file?
will @commands.cooldown(1, 10, commands.BucketType.user) work for the latest py version?
dpy*
either that or we make something like a GitHub pages that would be cool too
yeah
u need to handle cooldown error in ur error handler tho
no it is an attachment inputtedi n a slash command
yeah i got that
the cooldown just doesnt work, still allows me to use the command
yeah attatchment can be of any type im asking if its .txt
on application command error or on command error
weird show code
as i remember there is a different decorator for slash commands cooldown
yh 1 sec
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
time to check docs
it is
this ?
disnake has same for both 
probably
doesnt cooldown unfortantly
@slate swan try this
ok 1 sec
@slate swan it is txt
would i just replace it with the old one?
!d discord.Attachment
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
that is not helping at all
I can't find anything on the docs either
calm down lol i was checking docs
!d discord.Attachment.read
await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.
New in version 1.1.
yeah use the read method
it does not work
how does it not work?
what does that mean
is .read() enough
what do you get?
await file.read()
yeah
if file is the param name
await file.read()
u will get the data in bytes
bytes.decode(encoding='utf-8', errors='strict')``````py
bytearray.decode(encoding='utf-8', errors='strict')```
Return the bytes decoded to a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str").
*encoding* defaults to `'utf-8'`; see [Standard Encodings](https://docs.python.org/3/library/codecs.html#standard-encodings) for possible values.
*errors* controls how decoding errors are handled. If `'strict'` (the default), a [`UnicodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeError "UnicodeError") exception is raised. Other possible values are `'ignore'`, `'replace'`, and any other name registered via [`codecs.register_error()`](https://docs.python.org/3/library/codecs.html#codecs.register_error "codecs.register_error"). See [Error Handlers](https://docs.python.org/3/library/codecs.html#error-handlers) for details.
For performance reasons, the value of *errors* is not checked for validity unless a decoding error actually occurs, [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode) is enabled or a [debug build](https://docs.python.org/3/using/configure.html#debug-build) is used.
Note
Passing the *encoding* argument to [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") allows decoding any [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) directly, without needing to make a temporary `bytes` or `bytearray` object.
or just str()
yeah
``
so await file.read.decode(encoding='utf-8)
no
b'hello'.decode('utf-8')```
### or
```py
str(b'hello', 'utf-8')```
str(await file.read())
ok
@shrewd apex we need to create a list of features to explain 👀
mhm
I keep getting the same error with .read()
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/translator-bot-20/cmds/translate.py", line 20, in translate
print(translator.detect(str(await file.read())))
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/client.py", line 255, in detect
data = self._translate(text, 'en', 'auto', kwargs)
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/client.py", line 78, in _translate
token = self.token_acquirer.do(text)
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/gtoken.py", line 194, in do
self._update()
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'translate' raised an exception: AttributeError: 'NoneType' object has no attribute 'group'```
we have 3 options
- gist
- repo with bunch of readme and examples
- a github pages sites with like some docs lib like mkdocs
- error handling
- global
- per command
- converters
- custom context
we should take this to another server for discussion ig
1st or 2nd looks fast to do
yes i know we should
1 or 2
3 rd is also I'll set up the repo tmrw we can get a nuce ui
i'd take a part too
can someone help me with my error
that would be cool
show translate command code
import discord
from discord.ext import commands
from discord import app_commands
import googletrans
from googletrans import Translator
class Translate(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(name="translate", description="Translate a file to English")
@app_commands.describe(file="The file to translate")
async def translate(self, interaction: discord.Interaction, file: discord.Attachment):
if file.content_type[0:4] != 'text':
interaction.response.send_message("Please input a valid text file", ephemeral=True)
translator = Translator()
print(translator.detect(str(await file.read())))
async def setup(client):
await client.add_cog(Translate(client))
he is trying to detect the language that the text inside the text file is
yeah its a issue with the translator library
oh
can u try printing the text
doesnt look like this issue comes from the discord bot
maybe the content is empty
also keep in mind that some languages may not have same encoding as English so when decoding u will have to specify
That's a google translate library issue
Google it, there is a solution
like i worked on some translation stuff for webnovels some time back like chinese has codec cp 499 or 599 or something so u have to decode with those specific values than utf-8
it's not tho

try printing the str(await file.read()) and see whats inside
No one is reading me : (
https://stackoverflow.com/questions/52455774/googletrans-stopped-working-with-error-nonetype-object-has-no-attribute-group
!pypi deep-translator
i use this its smexy google rate limited me very often when i used googletrans ;-;
!source pip
Provide information about a specific package from PyPI.
also btw u would need to run this in an executor to not block they use requests internally i think
definitely need to add the concept of blocking or not in the guide
is that enough content for detection of a language 
Ahh actually.. I realized that i will not be available enough in the next two weeks... But i will try to do something, will see
Such phrase is enough i think.
but more standard - no
try it out ig no harm altho look into the error if its lib specific
ah
thats fine i suppose
I get the same error as before
mute the group :p
lib issue
do you know another library
@blazing flint
ty
Hello, suppose I use my Command Prompt to run the bot and host it on my PC but I want to hide the Command Prompt Console but still keep the bot running on the background, would that be possible? And is it possible to close it through Task Manager or something?
It's just obstructing to Alt+Tab and see a cmd console just sitting there.
I see some solutions online that is to change the extension to .pyw, but unsure if it would break things.
its \u200e
Look as per my knowledge we have 3 steps
1.
value="** **space"
space=" "
value=f"{space} ok"
And last one what downie said @coarse geyser
All three works for me
Probably the encoding of something or whatever else blocking it
Because encoding is different on machines duh
For the third time, it's called encoding
Yes, your computer also uses encoding to save files - very mind-blowing
And depending on that, it doesn't matter to whom you send - it will be sent with the encoding YOUR computer has used to save the file
Back to primary school topics
You don't send data to discord based on their encoding, they handle your data later on
And as mentioned above, it may be because of encoding, could be something else
Change your encoding or make sure it's sent with proper encoding
He doesn't know about it
?????????
Bro being racist 
Field Name: yes
Field Value: _ _ _ _ _ _ yes
So it's definitely something on your end
And the way you send the data to discord
Proposes some nonsense
Says thanks to own nonsense proposition
Will continue blaming others
...
Profit???
Ok.
Cool.

<@&831776746206265384> thank you ^-^
See context above as well with the user being racist
meanwhile Russians brute forcing your accounts
!cban 1116437317360554064 racism and trolling
:incoming_envelope: :ok_hand: applied ban to @coarse geyser permanently.
Thanks
carry on
Thanks
why do I get this error?
Because you did
message = message.content.lower()
So message is no longer a message object but just a string
oh ok
I didnt realise that i did message as the name
if f'2 {message.guild.id}' not in r:
return
message_content2 = message.content.lower()
words = message_content2.split(",.!?;:=+_-*%&!/\><~ ")
for word in words:
if word in profanity.CENSOR_WORDSET:
await message.delete()
embed = discord.Embed(title="No bad words please", description=None)
embed.set_footer(text="Censored by better_profanity")
log = r.get(f"log {str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
``` I have this code here to check if theres special characters in between words but its not doing anything
profanity.CENSOR_WORDSET is a set of bad words
no error
what has happened here
That space issue guy was being racist
ah what a nice guy
Ikr
😭
I play for a league that uses mystatsonline.com as a place to store all of our league's stats, but I was wondering if there would be a (relatively) simple way to scrape the info off the site to use for a discord bot aswell. I already checked, and sadly, there is no api for the site
someone can help me, i need a simple bot for my discord server, only 3 basic commands, but i dont understand too much, y alredy got a base code, can someon help me?
i only need this commands: $generatecode, $deletecode and $reclaim 'code', generate a 6 digits code that will be stored on codes.txt and $reclaim code will get 1 gift from a list, $deletecode will delete the code from the codes.txt
those are 4 commands
ammm no, $generatecode $deletecode and $reclaim 'code'
thanks, i alredy posted it
I need to import a fail safe incase someone tries to scam me, how can I delete all of the files of a bot across all servers?
So say I give a bot to someone, then they block me, ban me, etc without paying, I want to be able to run a command in my server, which the bot is still in, to destroy all of its files across all servers. I don't care if it destroies all of the files of the one I sent the command in, as I will have it backed up on a totally separate file.
Would this do the trick?
path = os.getcwd()
for file in path:
os.remove(file)

What if they just copy paste somewhere else or backup it
Also command wouldn't run if bot is offline
I don't think you have any luck
You shouldn't give your bot's files to someone unless you're 100% OK with them just running it on their own without giving anything back to you
Yea, but I want to give them a chance to be trustworthy
Another option is to host their bot for them so you're in control of the bot (if they don't pay, you can simply shut off the bot)
I don't have anything to host the bot, so I can't do that
Charge users for the hosting 
I could try that....
I got an old laptop I don't use
You can also charge users the cost of the product (the bot) + labor costs as a profit
So it's a net gain for you
Labor costs for moving my fingers, love it
Genius
Well you need to make a profit, otherwise there's no point
True
Do you know of a good place or server I can go to in order to find people that want my services?
Fiverr or Upwork
Got it
guys
im trying to make making a command easier, heres a ex
@commands.command()
async def ping(self, ctx):
await ctx.send("pong")
remake
def cmd(title, send)
@commands.command()
async def title(self, ctx):
await ctx.send(send)
so basically whatever is put in the title is basically gonna be the command name
send is for sending a message to the specified text
I quite don't understand what exactly are you trying

ok
so u know lua
function button(title, send)
guititle = title
guiresponse = send
for example
function button(game, hello)
guititle = title
guiresponse = send
command
app title is game and the cmd prints hello
@hasty pike heres a example
Is it my not working or you aren't telling me what do you need
No i talk in python and 3 different languages
okay
i need help with making a command creation simpler
like this
Just use the traditional method as documentation says
No need for self modifications
It's already alot simpler
This should probably be a dict mapping honestly
Make the triggers into keys and the responses into values, check in on_message
I want my bot to send some msg like "Failed" when someone tries to mute a user who has admin perms. How do I do it
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 58, in on_message_delete
snipe_channel = message.content.channel
AttributeError: 'str' object has no attribute 'channel'
tree = discord.app_commands.CommandTree(client)
^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'app_commands'
Code
How can I get like a few set args, then after that an infinite number of args that are put together into an array, and only the inf number of args are put into the array
For example:
async def info(self, context: Context, eventtype: str, notes: str, attendees: str):
I want to keep the first two, and I want an infinite number of attendees args, which are all put together into an array
You put * for that
Like
async def ban(ctx, user: discord.Member, *, reason=None)
@tacit prawn
You can do try except
try:
mute function goes here
except:
await ctx.send("unable to mute this member")
@winter token
Thanks
Wait, so it provides an infinite number of args how? Infinite reasons? Infinite unnamed args?
Don't quite get it...
What infinite number of args
I need to have two args, then after that I will have an infinite number of args
!e
def a(*args):
print(*args)
a(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
0 1 2 3 4 5 6 7 8 9
!e or this
def a(first, second, *args):
print(first, second)
print(*args)
a("uwu", "owo", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | uwu owo
002 | 0 1 2 3 4 5 6 7 8 9
there is no specific things like has_permissions?
@winter token you'll have to use an if condition ```py
if other_member.guild_permissions.administrator:
# member is admin
or maybe just handle BotMissingPermissions or MissingPermissions
also what is that profile sarth 🤔
You mean Aditi
Infinite words in reason
you don't need infinite args for that....
Yeah they were right
async def timeout(self, ctx, member:discord.Member, duration: converter, *, reason = "Not Specified"):
description = f"**Timed out:** {member.mention}\n**Timed out by:** {ctx.author.mention}\n**Reason:** {reason}"
embed = discord.Embed(title = "Timed out Successfully!", description = description, colour = colour)
if member.mention == ctx.author.mention:
await ctx.send("You can't timeout yourself.")
else:
try:
if member.is_timed_out() == True:
await ctx.send("The member is already timed out.")
else:
await member.timeout(until = duration, reason = reason)
await ctx.send(embed = embed)
Error occured: Command raised an exception: TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'
how do i use until thingy
Learn to read errors
TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'
remove until=
So use it
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.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
O can be datetime.datetime as well
In your case datetime.timedelta will be the best
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
it wont filter the input like 1d1h1m etc right?
yea i can do that to timedelta as well?
Would be best if the converter would already return timedelta
ok_words = "assesment", "assasin", "pass", "rass", "lass"
words = message.content.lower()
for word in profanity.CENSOR_WORDSET:
if word in words:
if words == ok_words:``` the ``if words == ok_words:`` doesnt work
No it takes only integers Like minutes=2, hours=5
breh
What does your converter output
time in seconds
so why dont you do something=datetime.timedelta(seconds=your_converter_output)
oh ty
Read up on how to get help and don't just say it doesn't work, we don't know what you want it to do
I just think that they're trolling at this point
🦆 Maybe
profanity.CENSOR_WORDSET is a set of words
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
!paste
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.
this code is deleting anything
when a message is edited
it should only be deleting profanity.CENSOR_WORDSET
Hi there, im trying to get more proficient with discord bots, right now getting familiar with cogs.
I've managed to get the hang of using commands in cog files, but trying to get certain attributes still doesnt work like it would in the main.py file:
import discord
from discord.ext import commands
from discord import app_commands
class Greetings(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@commands.command() # Actually introducing a command.
async def hello(self, ctx:commands.Context):
await ctx.send(f'Hello {ctx.author}')
#working
@commands.command()
async def shutdown(self, ctx:commands.Context):
await ctx.send("Shutting down the bot...")
await self.client.close()
#working
@commands.command(aliases=['uinfo', 'whois'])
async def userinfo(self, ctx:commands.Context, member): #member:discord.Member=None
#if member == None:
# member = ctx.author
embed = discord.Embed(title="User info", description=f"Here is the user info on the user{member.name}", color = discord.Color.green(), timestamp = ctx.message.created_at)
embed.add_field(name="ID", value=member.id)
embed.add_field(name="Name", value = f"{member.name}#{member.discriminator}")
embed.add_field(name="Nickname", value = member.display_name)
await ctx.send(embed=embed)
async def setup(client:commands.Bot) -> None:
await client.add_cog(Greetings(client))```
Its about the third @commands.command , how do i correctly get the name, member, author when .userinfo is called?
Getting *Context' object has no attribute 'name'* error and i roughly know why just not familiar with cogs enough yet to fix it :/
Any help is appreciated 
hello, how would i make it so even after restarting the bot, the button interaction works?
!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.
you'll have to make a persistent view
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
File "/home/alias/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/alias/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/alias/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'name'```
looks like you are trying to access .name on a string
embed.add_field(name="Name", value = f"{member.name}#{member.discriminator}")
member is a string so you cannot use member.name
look at the function signature, the member parameter has no typehint so discord.py will pass it as a string
You may want to go through https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html to understand how the commands are parsed
!rpc
A relative path is a partial path that is relative to your current working directory. A common misconception is that your current working directory is the location of the module you're executing, but this is not the case. Your current working directory is actually the directory you were in when you ran the python interpreter. The reason for this misconception is because a common way to run your code is to navigate to the directory your module is stored, and run python <module>.py. Thus, in this case your current working directory will be the same as the location of the module. However, if we instead did python path/to/<module>.py, our current working directory would no longer be the same as the location of the module we're executing.
Why is this important?
When opening files in python, relative paths won't always work since it's dependent on what directory you were in when you ran your code. A common issue people face is running their code in an IDE thinking they can open files that are in the same directory as their module, but the current working directory will be different than what they expect and so they won't find the file. The way to avoid this problem is by using absolute paths, which is the full path from your root directory to the file you want to open.
!sa
@raw rain please use #bot-commands for random commands
is there a way to set the footer at right side
ok
!d discord.Embed.timestamp
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
!paste
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.
@slate swan https://paste.pythondiscord.com/eheziyuqev - The /investiment / command doesn't even show when i try to use the command. No errors, got a clue why?
As far as i know discord bot can't listen or record voice in a vc
Guys any tutorial suggestions to build discord bots?
Look at the gist can't suggest any tutorial since the lib keeps changing
Oh okay thank u
Btw and smth else dont want to bother
I keep getting stuck even after finishing python bootcamps
When it gets to actual code
I blame a bit and my adhd but still
Any suggestions
Keep on practicing I'd say it's not easy to write a code
Yeah i guess lol
I Remember there was a feature in the mee6 that you could record conversarions in vc not sure tho
Don't know but might be interesting if it is
you can, however it's an undocumented part of the api and most python dapi wrappers do not have proper support for it (only some RFCs and forks which are experimental)
py-cord used one of discord.py's voice receive forks, but I'm not sure how much that has been polished
the only way to output a final message with information from three different forms is to use global variables, but if two people fill out the form at the same time then its possible for them to receive the wrong message. is there a way to avoid this
Yep you can record in mee6
use a dict?
host='redis-11943.c56.east-us.azure.cloud.redislabs.com',
port=11943,
password='pass')```
im using redis but its not working for example
```py
@client.tree.command(name="anti-discord-servers-on", description="blocks discord servers from your server")
@app_commands.default_permissions(manage_guild=True)
async def antiservers_on(interaction: discord.Interaction):
if f'{interaction.guild.id}' in r:
pass
await interaction.response.send_message("Anti discord servers is already on")
else:
r.set(f'{str(interaction.guild.id)}', 'on')
await interaction.response.send_message("Anti discord servers is on")
``` this doesnt work like it stores it but doesnt get it
command not working even after syncing:
@bot.tree.command(name="verify", description="Sends the verification button")
async def verify(interaction):
verifybutton = ui.Button(label="Verify", style=discord.ButtonStyle.green, custom_id="verifybutton", emoji="✅")
viewVerify = ui.View()
viewVerify.add_item(verifybutton)
await interaction.response.send_message(view=viewVerify)```
Is anyone familiar with sir Kryptox's bot template? I wanted to add a Welcome {member} feature and I opted to put it in bot.py, but upon testing it doesn't work. I think my code's right, but I dunno.
client = discord.Client(intents=intents)
@client.event
async def on_member_join(member):
channel = client.get_channel(...)
messages_title = [f"Hiya {member.name}!", f"Bom Bom Bakudan, {member.name}!", f"Let's go fish blasting, {member.name}!", f"Let's play, {member.name}!'"]
embed = discord.Embed(
title = random.choice(messages_title),
description = f"Welcome to {member.guild.name}! Say hello to everyone at {channel.mention}!",
color = 0x752C18)
embed.set_thumbnail(url=member.avatar_url)
embed.set_image(url=...")
await channel.send(embed=embed)
Make sure the members intent is set
it is,
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.presences = True
also on developer portal
Then likely have some error, for the channel use
channel = client.get_channel(...) or await client.fetch_channel(...)
instead
can someone help me
I'm sorry haha is that code one line or should I replace channel = client.get_channel(...) with that second one.
or like this?
Like that
can someone help me?
You should get errors though
member.avatar_url is not a thing, it's member.avatar.url
await client.send() is not a thing either, you probably want to either send in channel with await channel.send(...) or in another channel that you get by ID again similarly to channel = ...
Paginator help?
Is there any official documentation?
A walkthrough on action based pagination in discord.py - Pagination_walkthrough.md
I always just used this instead
https://github.com/Defxult/reactionmenu
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects. - GitHub - Defxult/reactionmenu: A library to create a discord.py...
It's still not working :< and console is so clean
I've been leaving and entering with another account for a few times
One pagination works for description, field and all or i need separate for them?
I also have on_member_remove set up and there's no effect too
one works
Dumb question but is the bot in the server
Also, what if you just add a print at the beginning
uhm yeah haha, all commands work just fine.
try:
except Exception as e:
print(e)
And what's the rest of your file
Always do this while testing commands
to check if the bot writes to console?
E.g. do you have some error handler eating everything
Yeah just add some print("test")
I just used your template as is, didn't change anything.
Thoughhhh I do have another bot in another console running, would that interfere?
you have bot.py on root though?
If the member joining doesn't have an avatar member.avatar.url won't work i think, try putting member.display_avatar.url that might fix it
aahh
I meant client
And yes, if you have both - it will not work
Only have one, you can do everything with one
yeah yeah I thought I should use client cause it's the one this tutorial i read used haha
Bot is pretty much Client with more things
So you can remove all client things and replace with bot e.g. @bot.event
hmm okay i'll try
And then you'll at least get errors if something goes wrong
never thought I'd be happy seeing errors on my code TT
Errors are more useful than nothing 
it finally works TT thanks very much guys
if i have a python program that prints on terminal can i make a discord bot that does that work?
Discord command to print on terminal?
no like
Like
didn't know that but thanks to you now i do
idk what its called
class approvedmodal(ui.Modal, title = "Approve Sponsor Request"):
message = ui.TextInput(label="Message", style=discord.TextStyle.long, placeholder="Your sponsor has been accepted!", required=True, max_length=2000)
async def on_submit(self, interaction : discord.Interaction):
user_id = int(interaction.message.embeds[0].footer.text)
message = self.message.value
creator_to_dm = interaction.guild.get_member(user_id)
if creator_to_dm == None:
await interaction.response.send_message("The user was not found as a member in the server.", ephemeral=True)
return
try:
await creator_to_dm.send(message)
await interaction.response.send_message("The Creator was successfully DMed. This request has been approved.", ephemeral=True)
for button in self.children:
button.disabled = True
await interaction.message.edit(content=f"This request was approved by {interaction.user.mention}", view=self)
except:
await interaction.response.send_message("Unable to DM the creator. Their DMs are closed.", ephemeral=True)
I am getting this error on the edit function when this modal is submitted
Error:
File "/home/container/creator_bot.py", line 3658, in on_submit
await interaction.message.edit(content=f"This request was approved by {interaction.user.mention}", view=self)
File "/home/container/.local/lib/python3.11/site-packages/discord/message.py", line 2275, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
what permissions does bot need to be able to autorole someone who joins? is it only manage roles?
and have a role higher than the on its giving
is there somewhere that I can see what permissions a permission integer checked?
I want to see if I missed something
what
Hi, i wanted to check for roles in the user executing the slash command
how would i do it?
!D
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
this¿
hmm
@commands.hybrid_group(name='test')
async def _test(ctx):
@test.command()
Is that the Right way to make hyrbid group
Because i can't see my commands in slash commands
like, i want it in a if statement
i want to restrict a role from using the command
@hasty pike can u help
You want to check if user has specific role or not
yeah
and if they do have it, then they cant use the command
Please read what I sent
how do i fetch it, bot.get_role?
.
how do i use the decorator
Read properly
Smh
Everything you need is given in documentation always
yea i tried that, but its making it so only people with that role can execute the command
Use predicate
how
Smh
def ignore_check():
def predicate(ctx) -> bool:
if role in ctx.author.roles:
return False
return True
return commands.check(predicate)
Try documentation next time
It would give you bunch of knowledge
eshaan after your done helping him can u help me with a command/embed please
everything works except for this 1 things
thing*
Just drop the question/problem and i will
im using cog by the way, im getting no errors too
can't i get the decorator value in a variable so i can use it in a if statement if its false then do this and if its true then do that
Commands in cog not working?

:D
embed name was originally called test, that didnt work too
That's what predicate do
@commands.command()
@ignore_check()
async def xd(self, ctx):
You missed self
ohhh
uh what
it works now, thanks
It is what you need
It's always better to read docs properly and understand things on your own
Np
i didnt understand, whats @ignore_check()
It is
Custom made check function
That's what i meant
guys how to make a url text in embed.set_footer thingy
ive done this
embed.set_footer(text="[hello](not tryna get banned)")
before this the () came first then [] right after
discord.Embed.set_footer(icon='url', text='yes')
u can see this one, in the footer it has a link with custom text
I don't think you can do this in footer
It's title or description
no?
Didn't work for me tho
.
oh ok
ok
How can I remove the hello and say command even though they aren't anywhere in the code anymore?
Should just work if you sync the command tree again but without the code for those two commands
Sync
Got it! Thank you both! 🙂
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/UnacceptableWittyAxis/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/UnacceptableWittyAxis/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/UnacceptableWittyAxis/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'whitelistrole' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
@bot.tree.command(name="whitelistrole")
@commands.has_permissions(administrator=True)
async def whitelistrole(interaction: discord.Interaction, role: discord.Role):
if not interaction.response.is_done():
update_whitelistrole(role.name)
await interaction.response.send_message("Whitelist role successfully updated.")
Defer your interaction and then u can send a follow-up later
This error is occurring because the interaction isn't being completed in the standard 3 sec therefore u need to defer it which inc the completion time to 15 min
can i ask what ctx stands for
usually "context", as in the class
ty
How do i do that 😭
The defer response, defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
When deferring, you get up to 15 minutes to respond instead of the normal 3 seconds.
This response is only supported if the interaction is an application command, component/view, or a modal.
Because deferring counts as a response, you can't use the typical response.send_message method afterwards. Instead we can use something called followup. We can use followup.send to send one or more followup messages.
Example:
await interaction.followup.send(...)```
Something to note: when deferring, if you set ephemeral to True, your first followup will be ephemeral regardless of what you pass to the ephemeral kwarg of followup.send. If you have ephemeral set to False, your first followup won't be ephemeral.
Docs on deferring: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.InteractionResponse.defer
Docs on followup: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction.followup
I have voice channel lock and unlock commands, but i dont want just anyone to use these commands.
I want to have it to where:
- The person who first joins the vc can use the commands
- Once that person leaves, it will either go the the next person who joined or reset it for someone else to use it(if that makes sense)
For example, if i joined a vc and left and someone else joins, they will be able to use those commands and i will be no longer able to because i wasnt the first one who joined.
https://paste.pythondiscord.com/ucepegufus
if anyone can could you send a link to a referred documentation.?
What documentation
U can just make a check to see wether the user is in the vc or not
i fixed my previous problem but now i have another one for channel.overwrites_for() how do i add a role to this
how do i fetch a guild in a cog? ```py
self.client.get_guild(id)
Seems to not be anything and shown as any
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild "discord.Client.get_guild") instead...
have you tried using this?
embed.add_field(name = "Bot Creation Date", value = f"{self.bot.created_at}", inline = True)
```
Error occured: Command raised an exception: AttributeError: 'Bot' object has no attribute 'created_at'
but in the docs there is
self.bot.user.created_at
can u send me link of bot object?
o
async def nuke(self, ctx, channel: discord.TextChannel = None):
if channel:
await channel.clone()
await channel.delete()
else:
await ctx.channel.clone()
await ctx.channel.delete()
await ctx.send("Channel Nuked!")
how do I make the bot send msg in the newly created channel
!d discord.TextChannel.clone
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
New in version 1.1.
Return type
abc.GuildChannel
target = channel or ctx.channel
new = await target.clone()
await target.delete()
``` and those if statements and repeated code is quite unnecessary
make the channel cloning a veriable like channel1 = await channel.clone then do await ctx.channel1.send()
How do I exclude certain cogs in the Slash Sync process?
Or does a Slash Command hide itself from you if you don't have the proper permissions to use it?
Because I want to hide my moderation commands in the Slash of my other normal users.
You can use the
@discord.app_commands.default_permissions(...)
decorator to specify the default permissions needed to see the command
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
So if I just use @discord.app_commands.default_permissions() that would do the trick, right?
I suppose
Note the warning though
You'll still have to check if the user has permissions to execute the command, e.g. with a decorator
Those are default permissions which can be edited at any time in the server settings, so you definitely want to add a has_permissions decorator
hi, ive made a program so that a user cannot press a button too quickly before it responds with Slowdown!, and adds them to usersoncooldown = [], however when the cooldown ends, the user isnt removed from the cooldown and therefore cannot reclick the button
i have no clue why
you'll have to show what ure doing
@discord.app_commands.checks.has_permissions(administrator=True)
So if a member is not an administrator the Slash Command won't appear right?
Why don't just test it
Also, and I just now thought I could check the code myself, this already does the trick?
i have removed it
Does itself
then ull have to show us the most important part of all of this, your code
You'll have to handle the permission error in an error handler if you want to give an error message back
Apparently not
wow so many decorators 😞
You haven't seen the average Java program then
okay default persmissions did the trick, thanks so much!

how do i make this print the date, month, year and time without the day?
f"<t:{int(member.created_at.timestamp())}:F>
Just use the default one, remove :F
And fyi, https://discord.com/developers/docs/reference#message-formatting-timestamp-styles those are the ones you can use
okay thanks
!paste



