#discord-bots
1 messages · Page 554 of 1
So, could u give code
@slate swan
# Importações
import discord
from discord.ext import commands
# Clasificação de classes
class Geral(commands.Cog):
"""Comandos gerais"""
def init(self, bot):
self.bot = bot
# Exemplo de comando:
@commands.command()
async def test(self, ctx):
embed=discord.Embed(title="Meu Criador", description="Sr abelha#5441", color=0xffdd00)
embed.set_author(name="Meu Criador")
embed.add_field(name="Sr abelha#5441", value="Youtube: Sr abelha", inline=False)
embed.set_footer(text="Bee Comunity")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Geral(bot))```
don't care about language
I Have this, How do I tell the program to delete 7 day old logs?
@client.event
async def on_ready():
date = datetime.datetime.utcnow().strftime('[%Y-%b-%d]')
with open(f".\logs\{date}.txt", 'a') as f:
f.write("\n" + f"{date} logs:" + "\n")
Ping me plz
not nearly related to dpy
help me
help me too!
Fix it for me and my mother is calling me to do homework
;--;
bruh
lost situation zarif
!d datetime.datetime.strptime
classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.
This is equivalent to:
```py
datetime(*(time.strptime(date_string, format)[0:6]))
``` [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime "time.strptime") or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
use that and compare it to utcnow() or now()
mhm?
And?
forgot the "
after button.click
what's discord.components.client
isn't it discord_components
so you don't use discord.py at all?
then why don't u use that
discord.ext.commands.Bot
what does that have to do with your current error
wait I just noticed
why are you calling event
there's no way the guy used @quaint axle.event() instead of @quaint axle.event
what error
you didn't finish the sentence
what does context mean
"discord.components.client" has no attribute
??
so then how did you define client
how did you use
client = ...
then you would get 'client' is not defined
just... how did you define client?
no, before the on_ready event
no, before that
!e
#string doesn't exist yet
print(mystring)
mystring = "Hello World!"
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'mystring' is not defined
client = discord.ext.commands.bot(prefix = your_prefix)
Well no, but it isn't the best way to do that
Yes 😂
then why don't you use @supple mortar
I use slash command so i don't use the prefix lol
@slate swan
He doesn't have a bot object named bot, he has a bot object named client
@placid skiff
BRUH HAHAHA he is right then
You declare your Bot object as bot
So you have always to use @bot and not @client
How do I make my bot speak through the command
I'm new to this group
I don't understand either
A friend recommends this group to me.
yes
like send a text-to-speech message or say something in a voice channel?
what do you have already?
And like !say and Bot speaks tended?
And like !say test
And the Bot speaks Test
did you understand?
in a voice channel
how can i stretch the button to the whole line?
like this
no idea about buttons
what's the problem aa_rav
well elaborate
nothing happens?
do you have an on_message by any chance?
hey hey, how to get the userid in a decorator??? I wanna do my own function, but since you can just get the context in it... how?
you wanna make a custom check?
yes
show code then
well just pass ctx to the check
then use ctx.author.id
you didn't call command
but how if the crx is not defined (since its the decorator=
@raven peak not @bot.command
!customcheck
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
uhh
someone?
Try using invisible characters.
bruh okay
\u200b and space not working...
how i can make it ? how can I take such a nickname format with a digital one?
!d discord.Embed.set_author
set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
if I use it {member.name} bot doesn't copy the user's digits
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/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/master/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/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
@slate swan
and how do I get the bot to completely copy the nickname with the user's numbers?
so {str(member)} or just {member} cause fstring converts
str(bot.user)
... Man thank you
np
SoMeOnE pls?
You can add some unicode spaces
\u200b
Just add this in the button content
Yups, it's a hairline space
wdym, how should I use it bruh
Or just try adding simple spaces
@maiden fable I don't understand you, I just tryied \u200b and spaces it didnt work
Okay, soooo lemme ask someone else. Someone I saw somewhere did stretch the button
@tough wagon just try adding loads of \u200b chars...
_ _
how?
Hi
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1635014367:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 16 consecutive newlines in 10s).

i finally found it - ⠀
I bet u used a selfbot cuz when a bot sent embed msg u can remove the embed and it gon look like that

And what if I say u r wrong? Prove that he's using a self bot
im just saying :3
Same (:

bruh
rude
Guys, how can I do that my bots writes in a embed emoji of my server

Like this one
Wdym?
Ah
I don't think so
Uhhhhhh, I don't think u can have an emoji in title
Try doing in the description
Emojis don't work in titles and footers
Yea thought so
alr
Not custom emojis at least, stuff like 🤧 work tho
\🥲
ty
See the emoji
Works?
No
Does the bot have access to the emoji?
Dyno also has the same problem
It does, its a emoji of the server where the bot is in
Mhmm..
oof
How do I find out who created the specific channel?
AuditLogs?
!d discord.AuditLogEntry
class discord.AuditLogEntry(*, users, data, guild)```
Represents an Audit Log entry.
You retrieve these via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
x == y Checks if two entries are equal.
x != y Checks if two entries are not equal.
hash(x) Returns the entry’s hash.
Changed in version 1.7: Audit log entries are now comparable and hashable.
Hey
Hi
how do I pass a image to my discord bot?
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
I want the user to attach a image and then I want to download that image
!d discord.Asset.download
No documentation found for the requested symbol.
await save(fp, *, seek_begin=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this asset into a file-like object.
There
thank you
A list of attachments given to a message.
This returns the list of discord.Asset objects
so ```python
@bot.command(brief='MF')
async def MF(ctx,attachment):
await ctx.send('pong')
?
how would I just download or get the url to the attached file?
Bro, I told u the whole way
Just loop through ctx.message.attachments and call the save method
Cool
can anyone help me run someone elses python bot
code is complete but i need a little help understanding it
i have a custom subclassed help cmd in a cog, is there any way i can use its functions in other cmds. for eg a user doesnt provide the right subcommands for a cmd so i could do like send cmd help for the context cmd
!d discord.ext.commands.Context.send_help
await send_help(entity=<bot>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Shows the help command for the specified entity if given. The entity can be a command or a cog.
If no entity is given, then it’ll show help for the entire bot.
If the entity is a string, then it looks up whether it’s a [`Cog`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") or a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command").
Note
Due to the way this function works, instead of returning something similar to [`command_not_found()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HelpCommand.command_not_found "discord.ext.commands.HelpCommand.command_not_found") this returns `None` on bad input or no help command.
thanks dude ;D
what are you guys using for bot development in python?
preferably a fork of discord.py
!pypi disnake
^^
How can i set custom status?
What type of status?
await bot.change_presence(activity=discord.Game("your coice"))
I think you can't
Yes I see
i can but how can i do idk
I think you can't set a custom status of a bot
i can
I don't know how so
You cant
see the top solution
Do you know how to get attachment url?
!d discord.Attachment.url
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
How can i set embed message?
@bot.command()
async def a(ctx):
print(ctx.message.attachments[0].url)
# prints url of first attachment
Editing an embed object or creating one?
Create
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, 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.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
Can i do it without class?
Thank you! (I forgot the [0]) 🙂
Wait i will say details
Actually i want to send message as embed from bot
You are not allowed to use that command here. Please use the #bot-commands channel instead.
!d discord.abc.Messageable.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
embed kwarg which takes in an Embed object
@bot.command()
async def a(ctx):
# make embed object
embed = discord.Embed(
title = 'title',
description = 'desc'
)
# send the embed
await ctx.send(embed = embed)
Do you know why when my bot send an embed, there is a on_message_edit event?
Ty but i cloudn't make it for ping
Can u help me
Do you want to ping someone?
ok wait a second
alr
round(bot.latency*1000,1)
Just do int(bot.latency*1000)
Wherever you want to show it
is there an error?
no
Yes
^
like this : title = "Pingim",
lol
it is working now tysm
hello! May anyone help me with components who knows a bit more about it?
I am currently trying to get button input and so far I'm getting the click event and after that something happens. Now I got 2 buttons and want to know: how to find out which button was pressed?
button_ctx: ComponentContext = await manage_components.wait_for_component(bot, components=action_row)
hi, what is wrong with this code, the discord bot should output an animated emoji, discord doesn't let me send the emoji id so it outputs :Fire:.
@client.event
async def on_message(message):
if message == 'wfire':
await message.send(":Fire:")
thanks
@client.command()
async def cmd(ctx):
youremoji = client.get_emoji(786138532069900350) # problem was here
await ctx.send(youremoji) # instead of formatting string simply use variable name
oh, ok
TYSM
its working?
can it be @client.event?
ok
@client.event
async def on_message(ctx):
if ctx == 'wfire':
await ctx.send(":Fire:")
didnt work
discord doesnt let me show the emoji id
but ik how to do it because i can do the add_reaction
oh
did i do it right?
client.process_commands(message)
isnt it the same code above
im not sure
i think you have to put the emoji id
and send it as a variable name
can anyone pls help 🥲
tbh i have never tried the buttons before
im new to discord bots
Yes
so, do I need somewhere to host the bot?
or do i just pass code to it and it runs as is
do you want it for free?
wym
wdym exaclty
like, lets say I make a bot
yes it can be
then you have to find a hosting server
What is that?
then why did it work for reactions???
What do you do?
hosting it on my computer
But the matter is different for you if you want to pay to subscribe or are looking for a free service but it is difficult to find a free service with all the required descriptions
Does it take a lot of computing power to do?
Okay, bc I do all of this on my laptop
You can try and watch the usage
And I don't want the bot to hinder my laptop's performance if I do host it on my computer
well idk lol
It does not consume much of your device
Try and see
Okay, how do I host it on my computer?
install the visual studio code
I have that
do you have the discord.py
I know all the necessary things for Python. I am just learning the Discord API rn
library
Yes i do
oh
now open the that have your disocrd bot code and run it
Don't have any at the moment
oh
you gonna run it once then its will be online but when you close the program or close your computer its gonna be offline
yes
yes
And that's free?
im not sure but most need to pay
Alr thanks
What I know is that there are two free services
replit: but it makes your bot code visible to everyone
What's the other
heroku: free and i dont think it will make your code visible to everyone and thats cool but its complicated
let me see
there is many
Do any of them stand out compared to what you have heard from others?
oh the replit itself you can paid and make your code private
Interesting
yes maybe
The paid service is always integrated and without problems
Alright thanks
welcome
If you need to run your bot 24/7 (with no downtime), you should consider using a virtual private server (VPS).
This is a list of VPS services that are sufficient for running Discord bots.
https://www.scaleway.com/
Based in Europe.
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
https://www.ovh.co.uk/
France and Canadian locations available.
https://www.time4vps.eu/
Seemingly based in Lithuania.
https://www.linode.com/
Cheap VPS.
https://www.vultr.com/
US-based, DigitalOcean-like.
https://galaxygate.net/
A reliable, affordable, and trusted host.
There are no reliable free options for VPS hosting. If you would rather not pay for a hosting service, you can consider self-hosting. Any modern hardware should be sufficient for running a bot. An old computer with a few GB of ram could be suitable, or a Raspberry Pi (any model, except perhaps one of the particularly less powerful ones).
Three distinct solutions to address your cloud infrastructure needs, your dedicated server solutions & hardware hosting
Helping millions of developers easily build, test, manage, and scale applications of any size – faster than ever before.
Affordable and powerful VPS Hosting in Europe. Linux, Windows and Storage VPS available from 1.99 EUR/month.
How would you get someones discord username from id
Yes, but what if I want to take commissions to make bots
Wouldn't a hosting service be better than using my computer?
Also, thank you for that entire list
Very much appreciated
async def "yours" (ctx, user: discord.Member)
maybe faster but not that much
oh
I am going to try to do that since I am currently enrolled
I sent an application to GitHub
For the package
cool
example
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member):
await user.kick()
gonna kick the user from his id too
The problems with the free 24/7 hosting options are
Replit:
• Code is public
• Shared servers so if someone else's bot gets ratelimited yours will be too
• Random restarts
Heroku:
• runs for 21 days/month without credit card registration
@final pumice
i tried using bot.get_user() but that returns nothing
let your customer handle hosting
That sounds like a good idea
have you tried mine
try
str(id) i think
But let's say they want to host it on their computer
I would have to give them the code, right?
@leaden jasper
Yes
wait ohh
I just understood
lol
str(bot.get_user(id))
he want his name
and id is 288098711400218624 for example
oh
@bot.command()
async def verify(ctx, ign):
id = ctx.author.id
print(id)
discordHash = bot.get_user(str(id))
print(discordHash)
If i run this and do the command the ID is outputted but discordHash returns as None
Ohh
Also yeah i didnt inclue the await ctx send but that was irrelevnat
sus
that still returns None
Ohhh ok
@bot.command()
async def verify(ctx, ign, user: discord.Member):
id = ctx.author.id
print(id)
discordHash = bot.get_user(str(id))
print(discordHash)
no wait
Alright that worked thanks
which kne
imps
one*
@bot.command()
async def slowmode(ctx, seconds: int):
await channel.edit(slowmode_delay=seconds)
await ctx.send(f"Slowmode delay set to {seconds} seconds.")
@client.command()
@commands.has_permissions(manage_channels=True)
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.channel.edit(slowmode_delay=seconds)
ye i saw
the ctx.channel.edit
damn
go and try await ctx.channel.edit(slowmode_delay=seconds)
i alr fixed my code
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
@boreal osprey
i alr fixed it
how do i
give a specific role to a user
temporarily
like a mute
for a specific specified time: 1 minute
@indigo forum You need to save the timestamp preferably in a database and have a task that checks if the time is up periodically to remove the role
uhh no thanks i prefer basic mute
well there is a more basic way, however it stops working after the code is refreshed
after giving the person the role, await asyncio.sleep(x) for the time given
when you restart the bot i guess
and after that line just remove the role
okay?
do you know when did i request the pass reset?
a lot of hours ago
this mornng
rn its 1:58 am
here
talking about the bot...
your bot is deezer?
uhh what woud be the entire thing
no, my bot is rickroll detector
and mutes for 1 minute to who sent the rickroll
pretty boring
but the mute not implemented yet
what
well
what i wanna do is:
-
check if the role "muted" exsists
- if not, create it
-
give the role to the user
and then
convert that to python code
Is that all your bot is going to do?
what the text "rickroll alert"?
⚠️ Rickroll Alert
Anything else
uhh no
when does it say that then?
when rickroll is detected
are u making the bot for fun?
... not really
so it's serious
how do you plan to host it
i mean a lot of effort for a bot that just detects rickrolls...
that is only 21 days per month without cc registration
that you can use /report to send me an email with the link using another email
I. do. not. care.
The bot will go offline in the last week of the month.
i said
I. DO. NOT. CARE.
what.
You answered "yes"
but contradicted that yes in your next message
So I'm confused.
i know
done
now
2 things to add to the bot
-make a "muted" role if it doesnt exist - ensure that the muted role has not admin related perms and admin perm and it doesnt have permission to send messages - add it to the user for 1 minute
-add a /report command so the bot uses an email and a password to email my alt email account with a brand new rickroll link (fake videos)
-the bot double checks it has admin permissions, otherwise, it automatically leaves the server
You also need to consider if the bot has permission to create and manage roles as well
OAuth does the job for the bot.
They could edit the url and mess up the permissions
but i guess it doesnt crash ur bot so dw about it
It's going to flood you with errors though if someone finds out how
edited: 3 features to add
rickroll bot with admin pwrmissions!?
ANTI rickroll bot
I don't think anyone sane would invite this bot to their server
uhh
Will you help me or discuss everything I say?
both i guess
I'm just pointing out that you won't get that many invites if your bot requires admin permission
can you translate this to human languag ?
message.guild.roles.cache.get('ROLE-ID').members.map(m=>m.user.id);
I have never heard of cache.get
oh wait
its js
is that old code?
v12
o
sorry i searched for js instead of py
this?
discord.utils.get(guild.roles,name="Supporter")
sure
but
how can i check if
that is true or false
and
how to implement it in my bot
this will return None if role is not found
so check if its None
@indigo forum :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'discord' is not defined
if discord.utils.get(...) is None
!e ```py
import discord
from discord.ext import commands
discord.utils.get(guild.roles,name="Supporter")
@indigo forum :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
why am I getting this error with bot.run on windows but not linux
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002A1B4FCA790>
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
@client.command()
async def timestamp(ctx):
x = datetime.now()
timestamp = x.timestamp()
await ctx.send(f'<t:{timestamp}:t>')``` How can I round the timestamp? It doesn't work with decimals for whatever reason.
wait
you're trying to close it?
why do you put :t at the end
no?
You need to, yes?
python has a bug with proactor thing on windows
um... no
so?
Wat
so why do I get that error ?
show your code
Is your bot for other servers or just your server?
int(timestamp)
wait nevermind I fixed it im literally stupid I made token a string which interfered with my error catching
because if its a public bot, you should use a db to store the muted roles for each server
@indigo forum
no need of storing them, just make them if they dont exist, ensure the correct perms, assign them, wait for 1 minute and unassign them
just use asyncio.sleep
Thank you!
are u using await asyncio.sleep(x) method?
that breaks when he restarts the bot
which is a lot since he uses heroku
i didnt implement the add role yet but yeah i use asyncio sleep
they restart every 24 hours
oh, that's a problem then
what.
db = await aiosqlite.connect('database.db')
cursor = await db.execute('SELECT time_expired FROM bans')
a = await cursor.fetchall()
for row in a:
await asyncio.sleep(1)
#print(row[0])
stored_timestamp = row[0]
if row[0] <= DT.datetime.now().timestamp():
muted = discord.utils.get(guild.guild.roles, name="Muted")``` So, I'm storing `time_expired` and `user_ids` in a database. How can I get the `user_ids` where the `muted` role is defined?
Wait- probably a question for #databases
How can I do that in my instance? It has to match up with the right row[0].
i dont know
If you're using heroku to host your bot for free, they will restart your bot once a day so your timed mutes with asyncio.sleep(x) will break
so you should store timestamps in a database
Keep in mind since heroku uses an ephemeral file system you will be required to use a database that isn't hosted on heroku
As it will reset all the data after reset
role1 = discord.utils.get(message.guild.roles, name='Members') Very dumb question, but how can I use this in a task loop (I defined the guild as guild)
!d discord.ext.tasks.loop @hollow agate
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
restart bot why?
@indigo forum its their policy i guess
oh and
i know its possible to host a discord.js bot in a website
i mean
inside the website
It's a free service and they transfer your hoster quite often-- get a vps or a cheap hosting
not giving money
not even a cent
You will need to learn databases xd
I use a hosting that's like $2 for 3 months and never restarts. lol
Go watch a youtube tutorial, there's quite a few databases you can choose from
SQLite is the easiest for me and generally the easiest.
cursor = await db.execute('DELETE FROM warns WHERE time_expired=?', (row[0], ))``` How can I make it just delete the time_expired data and not the whole row/column?

uhh probably this one? https://www.youtube.com/watch?v=Y9DzfPJsP2s
My discord server ► https://discord.gg/sfYjTSA
(If you have any questions or just want to have a chat with us)
(Some Cool Stuff)
Nertivia ► https://nertivia.supertiger.tk/
My server in Nertivia ► https://nertivia.supertiger.tk/invites/B4tMwO
Install discord.py ► pip install discord.py or py -3 pip install discord.py
Discord.py documentation ►...
That's part 5... go get a part 1 xD
True, you're gonna need to host a database somehwere else
uhh no because part 5 means part 5 of the bot in general
Then go figure it out.
how about github private repo
I don't know nor care-- figure it out xd
github is not a server
and?
uhh
cursor = await db.execute('DELETE FROM warns WHERE time_expired=?', (row[0], ))``` How can I make it just delete just the `time_expired` data and not the whole row/column?
rename the database to repo i guess
I still don't see how that solves the problem
cursor = await db.execute('DELETE FROM warns WHERE =?', (row[0], ))
ur suposed to give the solutions not the ones asking for help
You can't connect to a sqlite externally
@indigo forum just use heroku's database
how
You can, there are some services out there for that
how
I mean, yeah, I reckon you could
postgreSQL
free plan
Row Limit10,000
Storage Capacity1 GB
that's all you need for a rickroll bot
Yes
ANTI RICKROLL
NOT RICKROLL
and
btw do i have to add the heroku postgres to the heroku app itself or make another one?
it doesnt matter
Make sure the database exists somewhere, get the credentials to connect to the database
the database exist where?
yo guys, how can I check if a specific user receiving a message has the permission to do so? I'm making a report feature for a moderation bot, and I would like to make it so that when the bot sends the report message to the person the person who used the command wanted to, that person has to have admin perms first.
Add a check
The user if in a guild, has a guild_permissions attribute which, you then access the administrator attribute of that
!d discord.Member.guild_permissions
property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
ill make a group for helping me cause a lot more people needs help and i wanna do this as quick as i can
ill add friends
accept the request
add this decorator
@commands.has_permissions(administrator = true)
wait so can I just do this: ```py
if staff.guild_permissions() == "administrator":
do something
nevermind, figured it out. Thank you guys !
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
use the decorator if you dont want to use the if statement
makes things neater, less indents
If a specific user receiving a message has the permissions to do
any1 know why theres a red line?
This implies to me that its a target which they are checking the perms of, although I could be wrong
ah okay, thank you!
no why would they check if the receiver has admin perms
they meant for themselves using the command
For an example, checking hierarchy before muting someone. Checking if someone isn't admin before warning them, etc lol
they are using a report system/dm support im guessing
Seems like it, which is why I said this
which doesnt make sense.
@commands.command()
async def report(self, ctx, message: str, staff: discord.Member):
if staff.guild_permissions.administrator or staff.guild_permissions.moderator:
await staff.send(message)
embed = discord.Embed()
embed.add_field(name="⠀", value="Message successfully sent!")
await ctx.send(embed=embed)
else:
embed = discord.Embed()
embed.add_field(name="Oops!",value="Message could not be sent, as the person you tried to send it to, is not a staff member.")
await ctx.send(embed=embed)
So I was right
c u tomorrow ||@leaden jasper@pliant gulch@hollow agate||
guild_permissions.moderator?
i'm trying to make a report command, where someone can submit a message into the command as a parameter, then the bot will dm the message to a moderator, why isn't this working, and I made a server for me and my friend to test this and he is an admin, but i'm getting a forbidden error saying I can't send messages to them, but i'm the server owner?
That isn't a valid permission
lol, idk
The guild_permissions.administrator part is correct though
!SendDM andy Hello.
you're saying you need to check if andy has admin permissions present which is redundant.
whereas i'm saying in order to use the command !senddm you need admin permissions which makes sense
Look at the command they just sent 😂
yeah, how can I make it so that the bot will create a dm with the person specified as a parameter in the command, and dm the message that the user who was reporting something said?
they're vague
Well, staff is a discord.Member instance, so you can use send method of it
!d discord.Member.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
but I want to make it so that any user who wants to report something, and I want them to be able to only send to mods, since why would I want anyone else to see the reports?
"If a specific user receiving a message has the permissions to do"
I'm already doing ```py
staff.send(message)
receiving, idk sounds pretty specific
Its a coroutine
So you need to await it
i did
Ok then that should work
I did py await staff.send(message)
yeah, but it's still saying that I can't send the report message to my friend who's an admin in my server, even though i'm the server owner lmao
Normally dm support systems redirect messages to a channel for all staff to see. His system is inefficient because if a staff member is busy/offline/afk you won't know and you need to run the command multiple times for other staff members
returning a 403 forbidden error, which I suppose means that I don't have permission to do something.
That doesn't make any sense here, are you sure its erroring from this command?
Oh wait,
make sure the person you are trying to DM Has DM's on
how about this. how can I make it so that I can just make the bot automatically start a dm channel with every mod and dm this message to them?
ah okay, they could have that turned off in privacy and safety I assume.
Sounds quite spammy I would just do await staff.send
Yea, but you should consider handling that error
try-except will do
ah okay, and just specify a staff member (preferably one that's online)?
Yea
ah yeah, just thought of that lol
like this: ```py
try:
staff.send(message)
except Forbidden:
await ctx.send("The staff member you wanted to send the message to, has dms turned off!")
Yes
alright, let me give that a shot
Assuming Forbidden is discord.Forbidden
Else goes with an if statement/ elif statement
Does what the word means,
Except goes with a try statement
ohhh shit
It will try the code, then except an error
now i understand
If the error is received it handles it
yep
ty dude!
👍
@pliant gulch really basic question, I have the bot working, but I can only set the parameter message to be only one word, otherwise it sets whatever the word after the first word is, to be the staff parameter, how can I fix this?
You will have to change around your function signature a bit
maybe **kwargs?
You can use the * which in discord.py consumes rest
ah okay
I.e (arg1, *, args)
wait so I should delete the message parameter and put *?
Hence consuming rest
ah okay, so I should put "*" in place of the "message" parameter?
how will the bot know when to count the input as a staff parameter?
!unsubscribe
Should be (staff: discord.Member, *, message: str)
Which is why I said you will need to rearrange the signature
ah okay, so the * should go before whatever it wants to consume the rest of?
Yes
ah okay, that's really nice, thank you for the clarification.
Keep in mind due to the nature of the asteriks in discordpy means, arguments that use it have to be at the end of a command signature
So for here you pass staff first, then the message
ah okay, so the parameter that it is consuming, has to be the last parameter in the commands signature right?
Yes
ah okay, and I can just call the message parameter as normal right?
same as before right?
Same as before, but staff has to be given before it
But with it you can pass multiple words
yep, that makes sense, let me test it out. thank you again for your help, I will definitely ask you if i need more help, if that's okay with you.
Sure
@pliant gulch is there a way I can make an automute command? like check between a start time, and the end time, and how many messages they sent throughout the time period, and give them a muted role if they do exceed a limit?
Uh yes there is a very easy way to make a mute with a tempmute system
how can I do so?
That is if you know tasks, and understand how to do databases
Do you know some SQL?
Or have you setup a database before
do you know how I could make a command that can execute codeblocks that are passed to it?
nope, heard of it before, never worked with it before.
nope, never.
using the exec() function?
and providing tracebacks for errors that occur?
https://github.com/an-dyy/0x42/blob/a69d77e3acb901e317f1ec4f476c7992be7e0347/schema.sql#L12-L17 https://github.com/an-dyy/0x42/blob/master/src/exts/mod.py If you ever decide to learn heres mine which you can reference
And yes you would use exec for the codeblock thing
Uhh idk how easy it will be to explain but
Exec can take a dictionary, this is where you put variables in that you want to be able to reference
You then want to create a str and pass that to exec beforehand the dictionary which is your function
i.e ```py
exec(f"async def eval():\n{code}")
and I would pass their code in the "code" parameter?
Then you can pass your dictionary of variables
Well, I skipped a few steps
first you need to clean up the codeblocks
You can do this via strip
As the parameter will look like tildas
!e py codeblock = "code stuff```"
print(codeblock.strip("`"))
@pliant gulch :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | codeblock = "
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
ah I can't do it on discord
damn okay
could you just give an example of a basic code being passed to the command, in the form of a dictionary, and that should help me better understand the meaning of what you are trying to say.
So now that codeblock is cleaned up, you can pass this to this
replacing code
!d exec
exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
Keep in mind you very much want to make sure this command can only be ran by you
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Use this decorator and then it will only allow you to run the command
as it can be dangerous
how?
Well someone can remove all the files from your computer/where you host the bot
damn okay
or any other thing that can be executed by code
I can just make it so that only people with admin perms
can run it, this way not only me can run it, but people who I trust
If you trust your admins enough sure ig
okay, let me try to write this command
You just need to use has_permissions and pass in administrator=True
ah okay, also, what do you mean here?
^^
The the example where I reference exec, I used an fstring
There it uses the variable code
ah okay, I understand.
👍
Hey Andy,
hi sleep
can I use try-except to simply use ```py
except Exception as e:
say something
Uh
in case the evaluated code returns errors?
You could ig
are there other ways?
Yea, you can use traceback module to format the exception and send that back to discord
Although this isn't the final step
could you give an example? (sorry, i just have never used some of the things that you are mentioning lol)
what would be the next step from there?
It would look like exec(f"async def eval():\n{code}, variables) then afterwards you would do await variables["eval"]()
variables being the dictionary of variables you made
which can be referenced in the codeblocks
i.e if I had py variables = {"stuff": 1} I could then reference it in the codeblock via stuff
yeah, i don't think i'm going to do all those steps if they aren't necessary to make a very basic evaluate command, since that's all I want for now, since I have other things to work on lol
@pliant gulch how could I use the traceback module to format any errors returned from the command user's code?
!d traceback.format_exc
traceback.format_exc(limit=None, chain=True)```
This is like `print_exc(limit)` but returns a string instead of printing to a file.
Import traceback and use this
do I have to pass anything to it or just that?
ah okay, let me try it out
@pliant gulch py @commands.command(aliases=["e", "eval"]) async def evaluate(self, ctx, *, code): codeblock = f"{code}```"
end_code = codeblock.strip("`")
evaluated_result = exec(f"async def eval():\n{end_code}")
captured_errors = traceback.format_exc(limit=None, chain=True)
embed = discord.Embed()
embed.add_field(name="Code evaluation finished!", value=f"{captured_errors}")
await ctx.send(embed=embed)
tried this code, and I got a indention error
indention error where exactly?
the traceback is leading to this line: ```py
evaluated_result = exec(f"async def eval():\n{end_code}")
Hmmm I don't see a problem here? Can you print end_code
okay
I think you need textwrap.indent for that
okay, I just realized that i was outputting the captured errors i got, not the result
where should I put this?
You will need to redefine end_code and assign to to textwrap.indent(end_code, prefix="\t")
so replace what I currently have assigned to end_code and replace it with what you said?
Well, you can do end_code = what you had originally
then under that redefine it as end_code = textwrap.indent(end_code, prefix="\t")
How do you use jumpurls
Or just call textwrap.indent on strip
i'm just going to the first option, since that seems more clear to me.
@pliant gulch after calling this variable: ```py
evaluated_result = exec(f"async def eval():\n{end_code}")
in this line: ```py
embed.add_field(name="Code evaluation finished!", value=f"{evaluated_result}")

wait so I would have to do this?
yo so im making a giveaway bot
and the giveaway section works
but the reoll bit doesnt
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
@bot.command()
@commands.has_role('👑CEO👑')
async def giveaway(ctx):
await ctx.send("Lets start with this giveaway! Answer these questions within 15 seconds! ")
questions = ["Which channel should it be hosted in? ",
"What should be the duration of the giveaway? (s|m|h|d)",
"What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await bot.wait_for('message', timeout = 15.0, check = check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didnt mention a channel properly. Do it like this {ctx.channel.mention} next time.")
channel = bot.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send(f"You didn't answer the time with a proper unit. Use (s|m|h|d) next time!")
return
elif time == -2:
await ctx.send(f"The time must be an integer. Please enter an integer next time.")
return
prize = answers[2]
await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = 0xA5FF1C)
embed.add_field(name = "Hosted by: ", value = ctx.author.mention)
embed.set_footer(text = f"Ends {answers[1]} from now on!")
my_msg = await channel.send(embed=embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won {prize}")
@bot.command()
@commands.has_role('👑CEO👑')
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
try:
new_msg = await channel.fetch_message(id_)
except:
await ctx.send("The id was entered incorrectly.")
return
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won {prize}!")```
There might be another way
That doesn't seem to bad send the errors
But this is how I do it as well
@pliant gulch so I would have to define a dictionary beforehand called "variables" and what should I put in it? could you walk me through it?
erm well
You don't need a variables
I was just showing that as an example
exec will make a function eval and you call that
i.e in your embed you call eval()
could you give me an example?
eval()
can you vc rn?
exec makes the eval function
I can't vc right now
!e ```py
exec("def eval():\n\tprint(2+2)")
eval()
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
4
Oh you might want to change the name if you don't want to overwrite eval as well
wait so I could just do that in ```py
evaluated_result = exec(f"async def eval():\n{end_code}")
so can anyone help me with my code then or what
and replace "async def eval():"?
well, evaluated_result is worthless here
as exec returns None
Just, wherever you are sending the return of the command to
yeah, after I called the embed, it returned none for exec
Are you returning anything in the code you input?
As it only returns whatever you returned
i just tested it with a code block ```py
print("Hello world!")
and i added the evaluated_result variable as a field in an embed, then returned that embed, which returned none.
great thanks for the help
sorry, andy is busy helping me, maybe try the d.py server?
Yea, because it only returns whatever you returned in the code
if you did print it will return None
Check the terminal and you will see the print
ah, maybe trying return?
but if you want something returned you need to return it
return 2+2 in your eval command
this is a server for python and were in a bots channel
and it should return

