#discord-bots
1 messages · Page 457 of 1
example help command by my bot
@client.command()
async def help(ctx):
helpEmbed = discord.Embed(title="Commands", color=0x000000)
helpEmbed.add_field(
name="#help", value="Shows this message.", inline=False)
helpEmbed.add_field(
name="#ping", value="Returns bot's latency.", inline=False)
helpEmbed.add_field(
name="#purge", value="Purges a certain amount of messages. Default is 5. Define the number of messages after `#purge` declaration.", inline=False)
helpEmbed.add_field(
name="#join (aliases: connect, come)", value="Makes the bot connect to a vocal channel.", inline=False)
helpEmbed.add_field(
name="#leave (aliases: disconnect, fuckoff)", value="Disconnects the bot from a voice channel.", inline=False)
await ctx.reply(embed=helpEmbed, mention_author=False)```
THANKS
@wispy sequoia the help command is bad
!d discord.ext.commands.Bot.commands use this and loop through it
commands```
A unique set of commands without aliases that are registered.
@wispy sequoia Let's not copy paste the code and spoonfeed, also this isn't the best way to make help command
Indeed
embed.set_footer(text="")
Just tell Subclassed HelpCommand
Me who never did that: 
I'm not a pro man I'm just testing
I'm still learning
That's why we told you about a better way to make one, if you'd like you can implement it
Well, I am just tell you... Just adviced u. Either loop through the bot.commands list of subclass helpcommand
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(**options)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
I disabled the auto help command
Making api wrapper is pain 
Indeed
There's almost 100 endpoints left 
is manage server manage_guild?
Still need to improve requesting method and handle rate limits
Sad
Not discord btw
Mhm
ty
Spotify API 
help plz
!pypi Spotify
spotify.py is an asynchronous API wrapper for Spotify written in Python.
.....
Wait what 
Question?
okay so i have this and i wanna do <t:command_used_time:R> but its giving me this error:
Hehe
it is not handling the exception everything is working but i want it should show the embed if someone will give wrong input or if someone will use command in wrong way
code:
embed= discord.Embed(description=f"Occured on <t:{int(ctx.message.created_at)}:D>", color=discord.Color.random())
Nvm I'll make one more
int only accepts integer with different bases
not a datetime object
convert that to posix timestamp
then how do i make the ctx.message.created_at into an int
i want to use unix time <t:unix:D>
Hey can someone help me , my bot is doing executing commands twice due to these lines of code
async def initialise(): await client.wait_until_ready() client.db = await aiosqlite.connect("expData.db") await client.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int , exp int, PRIMARY KEY (guild_id, user_id))")
can someone tell me whats wrong ?
i used sqlite3.
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3.10/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3.10/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
ohh so i do ctx.message.created_at.timestamp()?

okay ty
@client.command(aliases=["knockout", "yeet"])
@has_permissions(administrator=True, kick_members=True, manage_guild=True)
async def kick(ctx, member: discord.Member, *, reason=None):
try:
await member.kick(reason=reason)
embed = discord.Embed(color=0x000000)
embed.add_field(name="\u2705 Success!",
value=f"Successfully kicked `{member}` with reason `{reason}`.", inline=False)
embed.set_footer(text=f"ID: {member.id}")
await ctx.send(embed=embed)
except:
embed = discord.Embed(color=0x000000)
embed.add_field(
name="\u26d4 Error!", value="An error occurred.", inline=False)
await ctx.send(embed=embed)```
This is the kick command, how to make a no-permessions member know why they can't run the command?
!d discord.ext.commands.CheckFaliure
No documentation found for the requested symbol.
lemme check console
:/
please someone help :/
k
discord.ext.commands.errors.MissingPermissions: You are missing Administrator and Kick Members permission(s) to run this command.
Yea
Can someone help me please.
With?
it didn't worked :/
Hey can someone help me , my bot is doing executing commands twice due to these lines of code
async def initialise(): await client.wait_until_ready() client.db = await aiosqlite.connect("expData.db") await client.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int , exp int, PRIMARY KEY (guild_id, user_id))")
can someone tell me whats wrong ?
i used sqlite3.
which error do u want to handle
Do u have an on_message?
every either value error or bad argument
yes
Hi
R u using bot.event or bot.listen?
bot.event
Sadly, nope
@wispy sequoia :/
Hmm, ok
wait ill share my whole on event
`@client.event
async def on_message(message):
if not message.author.bot:
cursor = await client.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)",(message.guild.id, message.author.id, 1))
if cursor.rowcount == 0:
await client.db.execute("UPDATE guildData SET exp=exp + 1 WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
cur = await client.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
data = await cur.fetchone()
exp = data[0]
lvl = math.sqrt(exp) / client.multiplier
if lvl.is_integer():
await message.channel.send(f"{message.author.mention} well done! You are now level: {int(lvl)}.")
await client.db.commit()
await client.process_commands(message)`
this is the on_message
hello @tardy lagoon
This isn't a place to advertise 👀
how i can except all exceptions ?
except:
not working :/
wait its giviing me a time which is not my local time which the command was used // its now 1543 for me but in there it says its 2043
MissingRequiredArgument is not raised inside the callback.
You need to make an error handler for this
?
unix time should show my current local time
how ?
Dpy raises it itself while calling the callback
1.7.3?
Make it timezone aware
how can i give an error when the author has permission but their role is lower
wdym
how
what discord.py version? 1.7.3?
how i can make that ?
uhh hold on
kk
yes 1.7.3
Maybe ask it in #python-discussion that how to convert a non timezone aware datetime object to utc timezone aware one.. I forget how to 
Also not sure what dpy gives as default
Maybe it calculates from your machine clock
no it works for account created and joined server but not for this idk why but its fine
yes
No idea then 
ctx.message.created_at.timestamp()
Try aware = pytz.utc.localise(<datetime.datetime>)
but i want timestamp
okay
install pytz if you don't have
it'll return aware object, now use .timestamp() on the return
One more way ```py
from datetime import timezone
dt = ctx.message.created_at # returns unaware datetime.datetime
dt = dt.replace(tzinfo=timezone.utc) # will update it with an aware object
Guyz someone can help me?
like not actual help
I just want to know the code for a notification bot for twitch insta and youtube
uh bruh well I have made a custom bot and I want to use only that bot in my server
it got almost everything just this bit is
uk difficlut
Learn how to make one then. There are a lot of wrappers for those apis
I dont know how to setup the apis
uh-huh?
You're already working with an API if you're making a discord bot 
no
am talking bout youtube and twitch api's
!pypi python-youtube
@client.command(aliases=["knockout", "yeet"])
@has_permissions(administrator=True, kick_members=True, manage_guild=True)
async def kick(ctx, member: discord.Member, *, reason=None):
try:
await member.kick(reason=reason)
embed = discord.Embed(color=0x000000)
embed.add_field(name="\u2705 Success!",
value=f"Successfully kicked `{member}` with reason `{reason}`.", inline=False)
embed.set_footer(text=f"ID: {member.id}")
await ctx.send(embed=embed)
except:
embed = discord.Embed(color=0x000000)
embed.add_field(
name="\u26d4 Error!", value="An error occurred.", inline=False)
await ctx.send(embed=embed)```
I want to make an except: for missing permessions, I already tried some ways but it's not working. How do I make it?
notification != download
forgot one bit am using .js lmao
help
discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
no no no
not a command error
a missing permession
like
Normal user: #kick user
Bot: You don't have enough permessions to do that
Whenever a check if failed, it's called a command error only...
but I want it to send a different embed for when a permession is missing
and also rn it's not sending anything if u miss a perm
this is when I try kick an admin/owner
but if u miss a perm it's not saying anything
Can I see the command error handler?
wym
^
it did what u wanted lol
lemme try kick a normal user
embed.add_field(name="Error!", value=f"{error}", inline=False)
``` maybe try this
you want it to send to the channel?
@client.event
async def on_command_error(ctx, error):
await ctx.send(error)
``` something like this
And use isinstance
yes
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3.10/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3.10/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union).
so
@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send(error)```
commands.MissingPermissions
not needed as I've imported the MissingPermessions lib
oh alr
i want help
with wut
how i can take a number as decimal also
u mean a float
ok so my question is, is it possible to run multiple discord bot tokens on one project, if yes, can someone help me do it
please spam my dms or ping me 100 times if u can help me with this
first mine plz
no u cant
really?
ive seen someone do it before tho
thank tho
thanks*
You wanna run 10 bots in a single file?
it's illeagal or againt ToS ig
because automation
Ok but is it possible
how i can do float calculations toooooo
uhhh sure ig if you find out a way
do you know how to do it?
wdym
no i tried before but it didnt work as intended
oh ok
float()
my brain hurt
but there i print the nums also but when i am doing 1 x 1 it is printing like 1.0 x 1.0
what
yes
thats how floats work
this
yes
what are u tryna do exactly? im lost lmao
i don't want this
then do int()?
then dont do float()?
but i also want ans of >solve 0.12 x 5
u have calculate floats and ints?
if float(num1) - int(num1) == 0:
it violates discord's TOS
discord bot client?
oh i see
but like if i want to check if the reaction is added bot then it should not perform the statements below
o
there's some client out there that gives you access to login to a bot account, so i thought... sorry 
its fine
this doesnt wait for the on_ready event, thus the bot is aways offline```py
@bot.event
async def on_ready():
print('go')
async def something():
await bot.wait_until_ready()
channel = bot.get_channel(12345)
while True:
...
async def something2():
await bot.wait_until_ready()
channel = bot.get_channel(12345)
while True:
...
bot.loop.create_task(something())
bot.loop.create_task(something2()) ```
guild = str(ctx.guild.id)
try:
giveawayid = self.giveawaychan[guild]
except KeyError:
giveawayid = {}
messageid = await giveawaychannel.fetch_message(msg.id)
giveawayid["messageid"] = messageid
self.giveawaychan[guild] = giveawayid
self.saveFile(self.giveawaychan, "giveaway.json")```
Error : `Command raised an exception: TypeError: keys must be str, int, float, bool or None, not Guild `
In which line u getting the error?
self.saveFile(self.giveawaychan, "giveaway.json")
File "D:\Discord Bot\ecrpgbot1-main\cogs\admin.py", line 222, in giveaway self.saveFile(self.giveawaychan, "giveaway.json") File "D:\Discord Bot\ecrpgbot1-main\cogs\admin.py", line 416, in saveFile json.dump(saveData, f, indent=4) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 179, in dump for chunk in iterable: File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 431, in _iterencode yield from _iterencode_dict(o, _current_indent_level) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 376, in _iterencode_dict raise TypeError(f'keys must be str, int, float, bool or None, ' TypeError: keys must be str, int, float, bool or None, not Guild
Print giveawayid
{ "824359600584523876": { "messageid":
now the json appears like this :3
prints {}
after it excuted the cmd it apears like this mising the [] and }
yes i am trying to save the message.id of the giveaway msg for a specific guild by saving them under the guildid
for this it gives Error : Command raised an exception: TypeError: Object of type Message is not JSON serializable
can't we save msg ids ina json?
read it again
carefully
also if possible change the naming a bit, it's getting so confusing
not able to interpret :3
yea sec
hm
guild = str(ctx.guild.id)
try:
gcid = self.giveawaychan[guild]
except KeyError:
gcid = {}
print(f"{gcid}")
messageid = await giveawaychannel.fetch_message(msg.id)
gcid["giveawaymessage"] = messageid
self.giveawaychan[guild] = gcid
self.saveFile(self.giveawaychan, "giveaway.json")```
Not for me
, it'll help you to interpret it easily
messageid = await giveawaychannel.fetch_message(msg.id)
you're saving message object in json not id
hm
4/5 messages edited 
i am too fast typer for my own good :3
how to dm a user if he react on a msg :/
@commands.has_role(ROLE ID)
or @commands.has_any_role(ROLES ID SEPARETED BY COMAS)
how to dm a user if he react on a msg :/
i want if someone will react on a msg then he will get dm from bot :/
ctx.author
then add a filter for this type of error commands.MissingPermissions
like if i want to do giveaway and the bot will give the code to user in dm if he will react
Please someone just tell how to let bot react if someone react on a msg
pls calm
not always people is going to help you they have their own problems
you need to add a filter for the error I said before
and if the error is the same then add something like -> await ctx.send('Insufficient permissions')
not exactly that
do you know the isinstance mehtod? to check values?
is it possible to make a bot send normal text and an embed in the same message?
how
then use it like this
if isinstance(error, commands.MissingPermissions):
#here execute the code
or the other options similar to what you did
guild = bot.get_guild(GUILD ID)
AdminRole = guild.get_role(ROLE ID)
if commands.MissingRole(AdminRole):
#Execute code here
lemme try
Guys is it possible to get the name of the cog by in which cmd is present?
@slate swan I want to get the name of a cog using a cmd
Like I want to know which cmd is in which cog
@slate swan But I recommend you the first way because can be used for every error related to missing permisions, because in the other you need to specify a filter for each command
But use what you consider better solution to your problem
Any way or directory?
here command.Cog
indicates the cog the command is
Thanks
@minor kestrel how can I get that cog, in the docs its written it is optional but where the cog arg
helpEmbed.set_thumbnail(url="https://puzzenti.github.io/images/pfp.png")
I mean where to write the cog arg
@slate swan
@minor kestrel
what?
how to add custom emoji like a nitro emoji in my bot
what you want is to get the cog where the command is isn't it?
then use command.Cog
wich returns the cog
and is you want the name use the attributes of Cog
what cog arg
how can i write this statement?
when x = y: do something
help @boreal ravine
Do \:emoji:
Then get the emoji markdown then paste it into a string or something
whats that server btw can u invite me?
x = datetime.datetime.utc.now()
futuredate = datetime.datetime.utcnow() + timedelta(seconds=timewait)```
want to make the giveaway end when x == futuredate, i was using asyncio.sleep but this gets interrupted when the bot is rebooted. how can i make the bot check for x == futuredate?
with a task
i dont know that, do you have some examples of it? how do i use it?
that would check if x >= futuredate like every minute
hm
u mean @tasks.loop?
yeah
hm , but if there is no giveaway it would send errors
wat
check if the variables exist
or when you have a giveaway, you start the task
once you've sent the message at the end, the task stops
hm
it doesnt
@tasks.loop(seconds=60)
async def giveawaytask():
if x and futuredate:
if x >= futuredate:
#get the message and send it
will you have multiple giveaways at once? 👀
i am getting the giveaway msg id from a json so it can be like if x is more than than of the message.created_at, then it should continue, else: do the task
testing bot bro
no, only 1 giveaway per guild
well that are multiple in a way i guess
do you get the futuretime from a json too?
wont this task make alot api calls :3
timestamp is better
prolly
get the futuretime, then if futuretime <= nowtime, get the message that was passed to the futuretime and continue
help i want to add this emoji in discord bot will it accept
isn't it like a database
this emoji
futuretime | message1
futuretime | message2
futuretime | message3
futuretime | message4
help anyone
isn't it built like this
aw man
if the bot is in that server, it can use the emoji like this
if the bot is not then
then it can't use that emoji
bru
if you're not in a server, you can't use that server's emoji either
ohk
but does the bot have nitro
yes
ohk thnx
how do i save time stamp?
how did u get this number whts the a
a \ before the emoji
three dots will it work
@slate swan bruh i already told u..
don't think so
Hi i am having an issue, I am using the event on_member_remove and then get the audit logs and filter them for kick actions async for entry in guild.audit_logs(action=discord.AuditLogAction.kick): this is to know if a user have been kicked even if the moderators doesn't use the command of the bot and do it by using the simply the discord option to kick a member. But there are some members that have been kicked by the bot, but instead of not doing nothing (as it should do based on the code below) it blame the kick action on another random moderator. Why is this???
Code:
@commands.Cog.listener()
async def on_member_remove(self, member):
guild = self.bot.get_guild(GUILD ID)
async for entry in guild.audit_logs(action=discord.AuditLogAction.kick):
if entry.user.bot:
return
#It should stop here but instead it blame it on another moderator
else:
#Execute code and send a message saying who kicked the user
the bot needs to be in the server 4 it 2 use the emoji
@slate swan
Audit logs can take some time to get updated and can give wrong results on instant fetch after action
see what
but i added the same emoji in my server
then is there solution? wait some time or what?
oh
?
send that emoji here with the backslash before it
ok
\:emoji:
Wait some time. Send a message without this info and maybe later update it 
ok
the thing is that it have been working for some time but since 1 month ago it started giving problems
await message.add_reaction("
716258118136234075")
no
the string is built up like
<a:emoji_name:emoji_id:>
await message.add_reaction("
716258118136234075")
yes
everything i need to paste in emoji send
await message.add_reaction(":Tadanimated:")
no
bru
yes
discord is just bullying me rn
mordex
is this some brawlhalla stuff? 
no name of Bot
ok but you need to paste in that long version
not just the name of the emoji
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
It's ^
THIS
Not Context.add_reaction
If it's animated
bro everything
kk
yes
Normal Emoji: <:emoji_name:emoji_id>
Animated Emoji: <a:emoji_name:emoji_id>
k
how do i do it?
its not working
Is the bot in the server with the emoji?
msg = await ctx.send('Hi!')
await msg.add_reaction(':emoji:')
<a:emoji:emoji_id>
guys how can i get all messages of channel ?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
but what you said is sus
@slate swanhow do i save the time ?
Hi, I'm using DC Webhooks to send message to channels in my server. I was wondering if there's any way to @mention under that message.
Is that possible?
mention a member?
import datetime
A role
!d discord.Role.mention
mention```
Returns a string that allows you to mention a role.
what was the @tasks.loop version for cogs?
Like I know the name of a command, now I want to get the name of the cog in which the command I got previously exists
<@&ROLE_ID>
how can i let my discord bot send msg at 8pm automatically?
pls tell
Everyday or what?
how to make a command where it can take in 2 arguments seperated by a comma
no like i started a giveaway and specified the time so bot should send msg on that time
Ah
Well, I ain't familiar with that type, but I think u will have to use the datetime module
I'd use https://github.com/gawel/aiocron Not for user reminders
What is your purpose
Calm down
Don't ping randoms and yea
I just asked them a question
Doesn't work and can we use or not are two different things
Yes? Why wouldn't you be able to do that..
like a command is >tellmehiat 6
so it should tell hi at 6 :/
i want to do this plz help
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'role'
[3:57 PM]
@commands.command()
async def rvc(self,ctx,role: discord.Role=None,channel=None):
channel=ctx.channel
overwrites = ctx.channel.overwrites_for(role)
if overwrites.send_messages==True:
perm = channel.overwrites_for(role)
perm.read_messages = True
await ctx.send("lol")
how will i correct this
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3.10/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3.10/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
!d datetime.datetime.fromtimestamp
classmethod datetime.fromtimestamp(timestamp, tz=None)```
Return the local date and time corresponding to the POSIX timestamp, such as is returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time"). If optional argument *tz* is `None` or not specified, the timestamp is converted to the platform’s local date and time, and the returned [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") object is naive.
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3.10/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the timestamp is converted to *tz*’s time zone.
How do i edit a message thats a variable inside another command?
flags = discord.PublicUserFlags
fl = member.public_flags
fe = []
f = {
flags.bug_hunter: ':bug_hunter_lvl1:',
flags.bug_hunter_level_2: ':bug_hunter_lvl2:',
flags.staff: ':staff:',
flags.early_supporter: ':support:',
flags.early_verified_bot_developer: ':developer:',
flags.partner: ':partnerbadge:',
flags.hypesquad_balance: ':balance:',
flags.hypesquad_bravery: ':bravery:',
flags.hypesquad_brilliance: ':briliance:',
flags.system: ':system:',
flags.verified_bot: ':verified_bot:',
}
for x, y in f.items():
if x in fl:
fe.append(y)
``` why is this not returning user badges? anything wrong?
flags is empty
Hola
Why do you even declare is
i want to get user's flags
That's not how it works..
then?
hi, how can i remove the load and unload commands from the help menu? kek ik other people can't run this because i've made it owner only but i don't want people to try to use it
@commands.command(hidden=True) # in cogs
@client.command(hidden=True)
#or
@bot.command(hidden=True)
Get the public user flags of the user, then use something like .bug_hunter on it and it gives a boolean back wether or not the user has this badge.
tenks :DDDDD
Hey can anyone teach me python for discord.....i just know the basics
do just slap it on to the end of @client/commands.command() in the brackets?
!reference
Whatever
so what I did is completely wrong?
!docs
Yes
ok
hm
!refer
Simply check, for example:
if user.public_flags.staff:
# user has staff badge
ohh
It returns a boolean
still banned from dpy 😭
same
thats why when i wrote the code before it said, staff=False
AttributeError: 'PermissionOverwrite' object has no attribute 'read_message'
it has attribute read_message?
read_messages
i am confused
!d discord.Permissions.read_messages
Returns True if a user can read messages from all or specific text channels.
hi, i'm not sure what i did wrong with the client.eventon ready thing can somebody help?
which database is best for economy command
closetime is not an event
i cant seem to except discord.MemberNotFound? everytime my commands.MemberNotFound is called
i want to run the function without a command how i can run ?
run it like a normal function?
{client.user}
but i want that the function should run at the given time
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
which database is best for economy command
thanks :D
wht the given minutes will do ?
dict base db's
run that function every 5 minutes
but i want to run that in given time :/
:)
then run it whenever you want
i can use it once by count = 1 ?
only this much?
but what you want will work with that
you want to check if a giveaway ended
flags = member.public_flags
if flags.bug_hunter:
':bug_hunter_lvl1:'
if flags.bug_hunter_level_2:
':bug_hunter_lvl2:'
if flags.staff:
':staff:'
if flags.partner:
':partnerbadge:'
if flags.verified_bot:
':verified_bot:'
if flags.verified_bot_developer:
':developer:'
if flags.system:
':system:'
if flags.hypesquad_balance:
':balance:'
if flags.hypesquad_brilliance:
':briliance:'
if flags.hypesquad_bravery:
':bravery:'
if flags.early_supporter:
':support:'
if flags:
em.add_field(name="Discord Badges", value=' | '.join(), inline=False)
what should i put in .join() ?
you don't want to just check it once and thats it
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3.10/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3.10/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
i cant seem to except discord.MemberNotFound? everytime my commands.MemberNotFound is called
like i start a giveaway by the command >gstart [channel where it will anounce] [time when bot will announce the winner]
dicts exist 
the bot should announce the winner once at given time :/
f = {
'like this?'
}
{flags.early_supporter:':support:'}
did that b4
then you have done it wrong
is this enough?
It's commands.MemberNotFound, not discord.MemberNotFound
it is? i tried to except that before and it wouldnt
Bots don't have access to these afaik
ill try it again
how to make a command that can take 2 arguments seperated by a comma
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
dpy has flags, bots do have those... wick bot shows badges of a user
It's in dpy
Hwo can i do so that if i press one button both of them get disabled instead of one being disabled ? (Bot the buttons in that view )
But bots don't have access to that endpoint
@bot.command
async def test(self, ctx, *, p):
p1, p2 = p.split(",")
await ctx.send(f"{p1} {p2}")
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
how to use that cog
First thing you're missing brackets in @bot.command()
Second thing why do you have self
Sorry for ping 😓
ohhhh
thanks a lot
rookie mistake
I think you need special OAuth scopes
help of cog? with HelpCommand?
i want to get the name of the cog
but how to use that param
?
cog.qualified_name
async def send_cog_help(self, cog):
title = cog.qualified_name
and then use in embed or send simply
command "test" is not found
that gets the cog name
missing () in bot.command
lol msg deleted ?
yea i got it pichu cleared my doubt thanks though!
ok
@dense swallow is it correct
async def test(self, ctx, cog):
await ctx.send(cog.qualified_name)
i want it for something else
to send in HelpCommand its not ctx, its self.get_destination, you can define a var
channel = self.get_destination()
await channel.send()
i dont want to get the cog in a help cmd i want to get the name of the cog separately
please help me
not in HelpCommand?
just in general?
Just try to make one. Look for tutorials on YouTube or seek sources on GitHub or Google. Ask here only if you have issues with your code.
i'm doing there is a prob
i want to get the name of the cog using the name of the cmd present in it but is it possible?
send_command_help(command)
ctx.command.cog ?
i am trying to get the name of a cmd from a other cmd and i want to get the name of the cog also in which the cmd is present
Command object has a parent attribute, which is the cog's name.
lemme explain u what i am trying to do
I can't help you too much since I'm on my phone. Try to search in the docs for the command object.
test is the name of a cmd
test2 is the name of the other cmd that is present in another cog
now i want to get the name of the cog using the name test with the help of test2
i wil use test2 and it will send me the name of the cog of test
ERROR:
Ignoring exception in command _eval:
Traceback (most recent call last):
File "main.py", line 1595, in _eval
f"async def func():\n{textwrap.indent(code, ' ')}", local_variables,
File "/usr/lib/python3.8/textwrap.py", line 480, in indent
return ''.join(prefixed_lines())
File "/usr/lib/python3.8/textwrap.py", line 478, in prefixed_lines
for line in text.splitlines(True):
AttributeError: 'NoneType' object has no attribute 'splitlines'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 1601, in _eval
result = " ".join(format_exception(e, e, e.__traceback__))
NameError: name 'format_exception' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: NameError: name 'format_exception' is not defined```
This is where the error is coming from:
```py
try:
with contextlib.redirect_stdout(stdout):
exec(
f"async def func():\n{textwrap.indent(code, ' ')}", local_variables,
)
obj = await local_variables["func"]()
result = f"{stdout.getvalue()}\n-- {obj}\n"
except Exception as e:
result = " ".join(format_exception(e, e, e.__traceback__))```
Command object has a parent attribute which is the cog's class.
what??
Read the last line of your error.
@hoary gust ctx.command.cog.qualified_name returns the cog name of the command that is used
how do i fix it
Read the last line.
bruh
can u plz show me a example how to use it
i mean how do i define it
I don't know what are you trying to do.
# cogs/testcmd.py
@bot.command()
async def test(self, ctx):
await ctx.send(f'This command belongs to cog: {ctx.command.cog.qualified_name}')
so this return testcmd
thanks
Doesn't it return the class's name and not the file?
No. But I guess he thinks it returns the file's name.
to resolve that u can just name the file and class same name lol
yes
ok thanks bud
👍
@dapper cobaltcan u help me pls... im trying to get user's flags/badges
flags = member.public_flags
if flags.bug_hunter:
':bug_hunter_lvl1:'
if flags.bug_hunter_level_2:
':bug_hunter_lvl2:'
if flags.staff:
':staff:'
if flags.partner:
':partnerbadge:'
if flags.verified_bot:
':verified_bot:'
if flags.verified_bot_developer:
':developer:'
if flags.system:
':system:'
if flags.hypesquad_balance:
':balance:'
if flags.hypesquad_brilliance:
':briliance:'
if flags.hypesquad_bravery:
':bravery:'
if flags.early_supporter:
':support:'
if flags:
em.add_field(name="Discord Badges", value=' | '.join(), inline=False)
what should i put in .join() ?
@dense swallow can u tell me how to get a cogs name from a cmd that is not in it
maybe
not for that
How could I make a temporal ban? any idea?
i only know for that, sry
ok
concept: member.ban() then await asyncio.sleep(days) then ctx.guild.unban()
probably not efficient
plz help
i want to get the class name from a differnt cmd that is not in that particular og
get the command using bot.get_command and then it should have some attr named cog or something I don't remember exactly
!d discord.ext.commands.Command.cog_name
cog_name```
The name of the cog this command belongs to, if any.
Yeah you can't just magically get a Cog namr, how and what from yoh wabt to get it
but how will it work?
wdym?
i mean i have the cmd name now i want to get the cog name of that cmd
^ 
Yeah so like what Akshu said
!d discord.ext.commands.Bot.get_command
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
ok maybe i get it
can anyone help me pls
how do i check if message is edited?
you should use somelist.append(':bug_hunter_lvl1:') instead of just a string
but then how do i make it into emojis?
@slate swan is it correct
cmd = self.bot.get_command("test")
cm2 = self.bot.cog_name(cmd)
print(cm2)
there is cmd.cog
!d discord.ext.commands.Command.cog_name
cog_name```
The name of the cog this command belongs to, if any.
it didnt work
define "didnt work"
@hasty iron is it possible to unload a cog from a cog
yes?
@hasty iron ^
!d discord.ext.commands.Bot.unload_cog
uh
ah
!d discord.ext.commands.Bot.unload_extension
unload_extension(name, *, package=None)```
Unloads an extension.
When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.
The extension can provide an optional global function, `teardown`, to do miscellaneous clean-up if necessary. This function takes a single parameter, the `bot`, similar to `setup` from [`load_extension()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension").
^
i have that thanks
Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.4.value: This field is required
i have put in values in every embed
Why doesn't this work? client.user.avatar_url
avatar_url
is this in a cog?
no
u forgot the ()
no, but it is 2.0
where?
what is the problem
nvm
avatar_url()
srry :/
no need.
still didnt work
what version of discord python are you on??
2.0
yes
it's avatar.url
oh
not _
okay
ty
new in v2?
yeah
changed
damn
pls pls anyone?
still didnt work
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'
help
default profile picture = no profile picture
yeah
oh
which will raise nonetype error
lol
either it's too much
too much?
anyone plz
send the embed
the code raises the key error
how to solve it?
em = discord.Embed(color=discord.Color.blue(), timestamp=ctx.message.created_at)
em.set_author(name = f"User-info of {member}")
em.add_field(name='User ID', value=member.id, inline=False)
em.add_field(name='Guild nickname', value=member.display_name, inline=False)
em.add_field(name='Account creation', value=f"{format_date(member.created_at)}", inline=False)
em.add_field(name='Date joined', value=f"{member.joined_at.strftime('%a, %#d %B %Y, %I:%M, %p UTC')}", inline=False)
if fl:
em.add_field(name="Discord Badges", value=' | '.join(fe), inline=False)
else:
em.add_field(name="Discord Badges", value=f'{self.bot.no} None', inline=False)
em.add_field(name=f"Roles ({len(rolelist)})", value=f"{roles or 'N/A'}", inline=False)
if member.bot:
em.add_field(name='Member bot', value=f'{self.bot.yes} Yes', inline=False)
else:
em.add_field(name='Member bot', value=f'{self.bot.no} No', inline=False)
em.set_footer(text=f"Requested by {ctx.author}", icon_url = ctx.author.avatar_url)
em.set_thumbnail(url = member.avatar_url)
await ctx.send(embed=em)
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
!rule 5 read it
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
sorry
hmm..
full tb?
tb?
i changed 4th em.add_field to this:
em.add_field(name='Date joined', value=f"{format_date(member.joined_at)}", inline=False)
what happened then?
Also I have another question, how do I show the number of bots in a server??
I know that len(ctx.guild.members) will show the total members, but how to show only the number of bots in a server??
len(bot_user for bot_user in ctx.guild.members if bot_user == bot.user)
same error
thanks
just try to print format_date(member.joined_at) and see what comes
no one reply here i am asking from 2 hours 😦
nothing came.. b4 i was doing it with error handler
if nothing comes, the value is empty
so the error is raised
not with this
gonna try that
you are trying to get an item from a list but the item indexed to what you want isn't there
ooo
Mon, Jan 11, 2021, 06:39 PM UTC
okay, it returns something
yea
im using that format_date to see the user's account creation
but wont return date joined, or that 4 embed value
who's account did you try on
mine
so that error is telling that the 4th em.add_field is empty?
it gives me this error
k
now I get this
whoops, sorry I used [()] instead of ([])
I need bot ideas
now there is another problem, it shows this when there r actally two bots in the server
I did a ModMail that everyone can use already(I mean not with docker stuff cause I donno how, but with config file)
Just got here, you have members intents?
yes
why are u using a modified discord client when you know it's illegal
Why is there if bot_user == bot.user
Is that betterdiscord?
yes??
You know that's against tos, right?
^
I am sorry, but how is that related to a question on a bot count command?
just saying lol
why?
It's not related, it's just you can't stay in the server while using betterdiscord
You should do bot_user for bot_user in ctx.guild.members if bot_user.bot
k
len([_bot for _bot in ctx.guild.members if _bot.bot])
Or sum(map(lambda member: member.bot, ctx.guild.members))
this one worked
thanks
If it's not used for anything harmful (e.g. themes) then Discord couldn't care less.
Rules are rules
yeah but discord said it themselves modified clients aren't allowed
Well, Discord doesn't really care, so why would you?
no way to prove that I broke the tos anyway
you clearly did
You literally sent a screenshot of the modified client and answered yes when I asked you if you use betterdiscord
He just used a theme which if you got mad over this you are just jealous imo.
check again
Deleting messages won't help, the server has logs of all messages
how is using a theme jealousy?
not images sadly (i think?)
I think yes?
possible
Anyway, what he wants to do is up to him, so we should just leave it here
Being mad because someone used a theme is jealousy imo. I don't get any comments on me using a github dark theme.

Isn't that the normal theme for gh?
It is ^
lmao

Which?
github dark theme
Light and dark themes are built in github already
Oh wait I think I got what you mean.
yes
Any modification to the discord client is not allowed
Are you saying that you're using betterdiscord as well?
Discord itself never cared when ppl modified their client for themes, I dont get why u r so pumped up about it
Not rlly we just said that it was against tos
Yes I am. But I'm not harming you or anyone in any way so I don't see a reason why you care so much tbh.
they said its not allowed, I am replying to that one
yes it's not allowed
I'm getting a keyerror, send help
We gone too off-topic.
Show your code.
also they said it was illegal, its not illegal, its just against the tos. If its illegal then betterdiscord would have gotten a cease and decease order
true
but I think I saw a chart where 5% of discord users got their account banned for client modifications
thats cuz they did harmful things with it. Most probably not for using themes
Mhm
<@&831776746206265384> This is just going off topic, talking about if betterdiscord is ok and stuff like that, stop it here please
we stopped? (2 minutes ago)
Not really
LOL
That was a pretty unnecessary ping tbh.
Api abusing maybe?
I don't know if you should've pinged the role
I see no reason to actually ping the Mods. No one is currently asking for help, and there is a better option for now which is @novel apex . I reported a few minutes ago about the problem.
@unkempt canyon deleted my message sorry
This is something ya'll brought up, so just stop it yourselves now
He gotta be trolling
Who?
It's fine, if the discussion is over then it's over, we can move on
Don't think he meant you.
oh i thought ...
No not you.
nvm
.topic cough
Suggest more topics here!
actually we did
its the problem with member.joined_at used to work fine
uhm an urban dict command 
alr imma paste the code it pastebin , then maybe you can see, otherwise @unkempt canyon is not letting me
Alright.
member joined server line... i changed its position , now it says embed.value 2
before it was 4
https://pastebin.com/regvWJ92 I'm getting a keyerror here even tho there is actually an attr. named data-src
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
It's for a bot
just do member.joined_at instead of formatting and try it
The docs say Member.joined_at can be None sometimes
why it is not changing the global StopTime ??
why it is not changing the global Stop Time?
it does return smth
pls tell
dont use globals
doesnt even respond lol
you can use a dictionary
what
??
"globals are evil"
i just want to change that :/
giveaway_config = dict(stop_time=0, giveaway_channel=None, participants={}, giveaway_active=False)```
aaaaaa wht is this i am seeing this first time :/
dictionary is mutable, so you can change it
its a dictionary
i should use it inside this function?
no




Then you should ask in djs