#discord-bots
1 messages ยท Page 1079 of 1
How do I make it show uptime in seconds
How to make embed paginator with slash command???
I'm using this but it keeps giving an error:
paginator = BotEmbedPaginator(interaction, embed_list)
await paginator.run()```
```discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: AttributeError: 'Interaction' object has no attribute 'bot'```
I've checked the docs and they only give examples of when `ctx` is used.
Is there any YT tutorial series for discord2?
No u
Hi can anyone give me library management system 6 page code
not any good one yet not like there were good ones in the first place tho
u have to make ur paginator either with reactions or buttons
wdym?
Oh welp, guess gotta experiment on my own through the docs. By the way, do you know how to use both traditional prefix commands along with slash commands?
u cannot both have different decorators/commands
so u can't have calling them both
Means python code for library Management System project
with prefix and slash at the same time
first thing this is discord bot channel
for that u should go to python help channel
So I just want toask
and here people help u with parts of your code or where u are stuck
Alright. What are message commands? Found this thing in the docs long with user commands but cannot understand what message commands are.
it's not a library like u ask a code and someone gives u one
Code transported from old laptop to new, but cant seem to find the correct way to install discord.py
any assistance please? ty
Ok I have made one but stuck at one thing
pip install discord
what's your python interpreter
not the right channel but seems like an easy problem
isn't it pip install discord2 or pip install discord.py?
there's no discord2
there is.
it's not a thing
!pypi discord2
already tried this w no luck
installed pip?
try pip install discord.py
@grizzled burrow
someone got a solution for this? ๐
@grizzled burrow maybe check the python version your vs code is running. Sometimes it uses a different one like an old version so that might cause problem.
cogs.player doesnt exist
why?
vsc
yeah but idk why cause it is definetly installed
installed or a cog?
installed
!pypi Cogs
WAIT NEVERMIND FOUND THE PROBLEM Xd
@shrewd apex Seems like you are AFK now but thank you so much for answering my previous questions. Really appreciate it mate.
@grizzled burrow when I click on the play button in vsc, it shows me this in the terminal
it means my python version is 3.9
what's yours?
just do python --version in terminal
Hey how to get emojis even if the bot is not in that server
not possible
unless u go personally and download the images by hand
then upload in a server ur bot is in
Asher's smort
I have seen many bots doing that @shrewd apex
do bot.get_emoji(id)
really how come my bot don't got such super powers then
it can only fetch from the servers bot is in otherwise u will only get the emoji name and id
yeah ik
Dont know but this exists
doesnt
@slate swan
lmao it doesn't exist no matter how many people u ping that won't change
sorry.....if I did anything
also how do u know this exists?
how do u know all the servers ur friends bot is in๐คจ
What exists
bot which sends emojis from all over discord
without being in the server
!d discord.Client.emojis is what u can use, but the bot can only send emojis of the servers it's in
property emojis```
The emojis that the connected client has.
is it possible to put slash commands in cogs?
yeah that's what we are trying to explain from 5 mins
Yea
where is ur rich presence๐
I'm on mobile rn
can you explain to me how?
oh sed
what was that lib again ? for that
Also, the GIF is like 1 GB and I cba to download it, upload it to websites to compress it, upload it to imgur and then use it
!pypi pypresence
ss taken
what's cba?
sounds like a military ship
Can't be arsed
!d discord.ext.commands.slash_command
No documentation found for the requested symbol.
lmao
Sad, dpy hasn't implemented those
dpy 2.0 new docs aint exactly pro it's seriously under documented on many functions and uses
Bro...
?
await read()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this asset as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") object.
Yeah i was asking for it
lmao the first thing that caught my eye was the name of the bot
๐
Dont see it
its secret
it took me a sec to come back to the question
Yeah that's why you understand it i think
Anyways, use a PartialEmoji converter and use the read method
me hunter sarth all indians
async def emoji(ctx, emoji:discord.PartialEmoji):
pic = await emoji.read()
do sending emojis in message generate links in message.content?
Ohk
i try it wait
What links
It's gonna return bytes BTW
U might wanna use BytesIO and pillow ig
so ive seen bots reply to commands with messages saying "only you can see this message" and whatnot, how is this done?
I am using pillow already
normally when u right click on emoji u get a pop up open emoji in new tab so if u send a message with the emoji will the link be generated for the emoji image
ephemeral=True when u r using slash commands/buttons/context commands
basically any interaction stuff
Yes
Yes
you can simply ```py
f"https://discord.com/emojis/{arg.strip("<>:a")}"
rip flantic bot
but u cant send it as emoji only as a image
I hate its owner he was my old friend now he is changed doesn't talk with us also
true, but that ss he sent was just an image
is there a way to upload a emoji using a bot?
yeah just saying to him
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
this
I was using discord.Emoji
nice thx
So it returns only the emoji that the bot is in *
ss taken again
What
in discord2, my message.content is coming out empty. I think that's because of the intents and stuff but how do I add intents to discord.Bot?
screen shot
๐who taken
for that method?
ur bot develepors page
are you using pycord or something?
yes
hm, disocrd.Bot is a thing for that lib only
It has that enabled there.
idk abt pycord but do u have all intents enabled in code like discord.Intents.all()
!intents this is how you do that in ur code
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
ok im trying to add slash commands to my bot which ive done with many in the past and its working great except that when i install discord-py-slash-command it says it failed bcs the version im using is too recent, how can i fix this
I need help with discord-py-slash-command, i installed it with pip install discord-py-slash-command but i still have an Error with the Import.
When i searched for the installation path i only saw 1 of 2 packages for discord-py-slash-command..
im having the same problem
are u not using discord.py 2.0?
do pip freeze
ok
i got a bunch of letters and numbers
discord.py @ file:///home/runner/.cache/pypoetry/artifacts/8a/f5/fd/3bad86524984f03dbed9b681a493a9b38c68e74a324f4a81b2143086b0/discord.py-1.7.3-py3-none-any.whl
@shrewd apex
it's 1.7.3
;/
get 2.0 and migrate that has slash commands in it
so is my other project where i have working slash commands
don't use third party lib
Asher's smort
since u want to use interaction u will sooner later need to migrate
better do it now then
prob like their username
pip install -U git+https://github.com/Rapptz/discord.py
https://discordpy.readthedocs.io/en/latest/migrating.html <- updates
install v2 -> pip install -U git+https://github.com/Rapptz/discord.py (you need python 3.8 or later)
install git (if required) -> https://git-scm/downloads

I wasn't making fun of anyone, and stop with that
lmao just jk๐
uninstall discord-py-slash-commands in the mean time
sorry
command*
it never installed thats the problem
yeah
๐ข yes yes
pip uninstall xxx
:p
oh and now i need to list intents... great i have no idea how to do that anymore xD
ew
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
see the code block
Why uninstall those tho?
im just taking it from an old project
that was a joke ofc
i used em a while back... and failed but the intents work
๐ข
make sure to add . message_content intents if you need message commands too
Its new in 2.0
just do discord.Intents.all()
did
I wish I was able to do that in a verified bot
also bot is at least running now, what next
u can't?
unless you don't get data whitelisted for that intent, no
btw u know how to shard a bot?
me?
nah
ok
you don't need any manual stuff for that, just use AutoShardedBot instead of Bot
my bot is online now how to do slash commands?
wdym by data whitelisted for the intent?
u have slash commands defined?
no i had to remove all the "import slash commands" stuff and the "slash = whatever" bcs i got an error saying they werent things
U need to manually apply for intents
Discord has all the right to disallow that
Tho u just gotta request for previleged intents
@shrewd apex no module named "discord_slash"
My bot has access to Message Content and Members
โ๏ธ
why tf did they remove this page
it was really useful
ik
i had a similar experience a month ago
i went to find a tutorial for cogs and it worked great but then when my friend wanted to learn they had removed the tutorial
@shrewd apex
eh well this page existed for like 3 yrs and more
Prolly they broke their website just like they break their app and api
maybe, im not surprised
lmao
yeah they just keep changing the date there tho it was April before
yeah they extended the date
It is the first time the realized that their API was buggy as hell (the ctx commands part), so they postponed the impl
how can you specify server icon?
property icon```
Returns the guildโs icon asset, if available.
for member is member.avatar_url
if you just mean getting its link, its guild.icon_url ( for you)
it wont work for servers with no icon, whats the error?
didnt they removed it in 2.0?
no error
i have 1.7.3
How do i make the bot create a certain role in a guild such as "Verified" if there's not one at the moment? Much appreciated if i could get some help on this
they say they use member.avatar_url so isn't it obvious yhat they are on 1.7.3
that wasnt my question lol
well, yes they did
nice
Anyone?
All the image related resources are Assets now
it works now i messed it up
yup
my fault
create_role
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
first use utils.get to get a role named Verified
it it exists, pass
else use Guild.create_role
once didn't have that and i created like 300 roles with same name by the time i checked
@slate swan does this look right at all?
import discord
from discord.ext import commands
import os
import asyncio
from discord import app_commands
bot = commands.Bot(command_prefix = "; ", intents = discord.Intents.all(), case_insensitive=True)
bot.remove_command("help")
@bot.event
async def on_ready():
print("Bot Status: ONLINE")
@bot.tree.command()
@app_commands.describe(test='Test Command')
async def test(interaction: discord.Interaction):
"""Test Command"""
await interaction.response.send_message("Testing")
bot.run(os.getenv("token"))
use bot.start now
since u are on 2.0 anyway
instead of run?
no you have to sync your commands in dpy
have a look at the docs
F , how did you manage to delete them? an eval?
i burnt the server ๐
i don't use dpy for app commands so no idea
it was a month or two ago when i first started with bots
If it exists, pass? can you give me an example ?
and then they said dpy dead
i stopped and waited for updates
now started with 2.0 again
ig most people jumped ships when they said dpy was dead
role = discord.utils.get(guild.roles, name,="role name")
if role: pass
else: role = guild.create_role()
just do if not role
im so lost...
well it was unmaintained for like 7+ months
Is there anything necessarily wrong with it?
saviour
yeah
huh? i dont understand the question
Only thing I'm seeing that's wrong is you need an app_commands.CommandTree instance
import discord
from discord.ext import commands
import os
import asyncio
from discord import app_commands
bot = commands.Bot(command_prefix = "; ", intents = discord.Intents.all(), case_insensitive=True)
bot.remove_command("help")
MY_GUILD = discord.Object(id=981206560481083492)
@bot.event
async def on_ready():
print("Bot Status: ONLINE")
class MyBot(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
@bot.tree.command()
@app_commands.describe(test='Test Command')
async def test(interaction: discord.Interaction):
"""Test Command"""
await interaction.response.send_message("Testing")
bot.start(os.getenv("token"))
And you'd do @tree.command()
no
I'm not understanding why you have both a client and a bot
If you're using slash commands, you only need client unless you're doing the whole hybrid command shenanigans
async def main():
async with bot:
await bot.start(token)
asyncio.run(main())
ohr
and i was already losing interest in it so i migrated
There should be some examples on the github for you
@vague sparrow this ?
If you want to do what you're doing, you should subclass commands.Bot and and use it as instance
im legit banging my head on my deck trying to comprehend this... it hurts to think about it now...
yeah i suppose would migrate too but i just started my second bot on this will prolly migrate after this and learning a but more started python seriously arnd 2 months ago
no object named token
ur token lmao
not the env
i put os.getenv(token)) and it didnt work
oh bruh
Also fwiw your CommandTree doesn't have to be bound to your discord.Client instance
my brain is dead, i forgot the quotation marks
os.getenv('token')
yep
Traceback (most recent call last):
File "main.py", line 19, in <module>
class MyBot(discord.bot):
AttributeError: module 'discord' has no attribute 'bot'
class MyBot(discord.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
commands.Bot
i still like normal command better with prefixes
bot = commands.Bot(command_prefix = "; ", intents = discord.Intents.all(), case_insensitive=True)
bot.remove_command("help")
MY_GUILD = discord.Object(id=981206560481083492)
@bot.event
async def on_ready():
print("Bot Status: ONLINE")
class MyBot(discord.Client):``` why?????
it's like u type pls anywhere and u know it's dank memer makes your bot unique kinda i suppose
@bot.tree.command()
@app_commands.describe(test='Test Command')
async def test(interaction: discord.Interaction):
"""Test Command"""
await interaction.response.send_message("Testing")
it says TypeError: unknown parameter given: test
no i did that bcs the server im using it in already has a bot with that prefix so to stop them from giving replies to the same command i added space
nah just sharing my opinion
as a link
i fixed client
git link to clone i use that in heroku
discord.py @ git+https://github.com/Rapptz/discord.py
like this
@bot.tree.command()
@app_commands.describe(test='Test Command')
async def test(interaction: discord.Interaction):
"""Test Command"""
await interaction.response.send_message("Testing")
where is the unknown parameter "test" that was given?
Dpy server
I haven't used dpy's slash command yet, but I'd assume the test='Test Command'
meanwhile danny getting mad for people using bot.http
wdym by channels even bot can't see
That's out of context
i didn't even know a beta tester channel was there till a guy told me to do ?tester
oh ok
@shrewd apex @slate swan @sick birch my bot is actually running but the commands arent showing up on discord
Did you sync?
was the bot invited with application commands scope ?
did you sync the command?
was the guild id correct?
Also get rid of the copy_global_to or whatever it's called
If it's a global command so it might take some time
If that overrides them as global commands it can take up to an hour for them to propagate
all correct i think
do client.event functions run as a thread?
@client.event
async def on_message(message):
# does this run as a thread?
@slate swan the only one im not sure about is syncing
pls explain how to sync bcs i dont remember...
"discordpy enjoyer" what a cringy name
yes
if it's synced it takes upto an hour to load since u got no error it's prolly synced
but it should still work in dms immediately right?
not in a guild sync*
for global functions
how do i make it global
idk i haven't used slash commands just speaking from what i have seen or heard
just check the docs
while hikari doesnt even need guild ids explicitly
do you have a setup_hook?
yes
yeah thats because of the new api...
gtg for a bit b back soon
just sync the commands in there using self.tree.sync
I mean, you have to manually pass in a discord.Object for dpy and guild ids for disnake/forks..., hikari does that automatically while allowing to over-ride default guilds
wait do you mean that hikari automatically figures out a default guild?
If none is provided?
sorry if i sound dumb, I quite didn't understand wym there
how do you make a timestamp?
(yes, i am dumb)
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
?
thats how you create a timestamp~
yeah
i have 11 syntax errors
with a datetime object as the argument
you are doing something wrong.... 
i want to make a timestamp with datum of the day when he/she executed the cmd
format_dt doesn't exists
yes that. im dumb
u can just use datetime lib
no it doesn't do anything like that
you may feel that the commands are guild specific but they are global
try it and see
Do you want it to by dynamic or just plain-text?
!e
import datetime
Tim = datetime.datetime.utcnow()
print(Tim.timestamp())
@shrewd apex :white_check_mark: Your eval job has completed with return code 0.
1654106016.028388
If it's dynamic it changes depending on the person looking at it according to their locale
just a text
uhh, thats weird
i want it on pillow image
u can change tz info if u want
Ah okay, in that case use the .strftime() method
i used that but it didnt work
What did you try? How does it not work?
thats how it works lol, don't you check the logs?
if they were guild specific it logs Processing Application commands for...
.strftime('%d, %m, %y')
its %b for months, i may be wrong
thats date month and year?
i know
oh
oh wait, yeah am going insane, im severely dumb
M is for month iirc
!e ```py
import datetime
print(datetime.datetime.now().strftime("%d %B or %b %y"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
01 June or Jun 22
oh thx
there is even a datetime.date
!e ```py
import datetime
print("<t:",datetime.datetime.now().timestamp().int(),":R>")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<t: 1654106320 :R>
t denotes that its a timestamp
R is the type of timestamp (stands for relative)
oh ok
cause mobile phone lol
do you mean timedelta?
timedelta object?
yes
where do you want to use it?
subtract two datetime objs
+5y
how to make spoiler?
oh ok ||thx||
np
thats not a spoiler, thats a timestamp :p
?
to add 5 years
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
!e ```py
import datetime
print(datetime.datetime.now()+datetime.timedelta(days=365.25))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2023-06-02 00:04:09.425021
do i need to use class?
no
ok
๐๏ธโโ๏ธ just see the example above
i almost forgot every year has 1/4 day extra adds to leap year
lmao u pretty smort for remembering that
well a day matters
yeah i might say if someone asks but definitely won't remember to use in code
not the best way but
@group()
async def command (ctx, *, false_arg):
if ctx.invoked_subcommand is None and false_arg:
# wrong command
i realise that this is the worst code i could type ( based on the spaces)
error type object 'datetime.datetime' has no attribute 'timedelta'
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
await self.tree.sync()
```?
because you did from datetime import datetime 
gunniteee asher
await add_roles(*roles, reason=None, atomic=True)
What is the * for before roles?
night, have a good one, sleep most probably
kk
you need another comma and space after it, it makes the following args endless
basically unpacks a tuple/dict
still the same error
!e ```py
print (*(1, 2 , 3))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1 2 3
all these arguments are different args instead of a single tuple there
show code and import
!e ```py
print ((1, 2 , 3))
@wet crystal :white_check_mark: Your eval job has completed with return code 0.
(1, 2, 3)
alr thanks
@slate swan like this?
no? read my code again maybe...
bcs the command still dont show up
expire = datetime.now() + datetime.timedelta(days=365*5)
that basically is triggered only when the subcommand you provide is not a subcommand
from datetime import *
@stable leaf don't you see any difference?
isee
did you pass in the object?
pass in the object... i dont understand
you forgot a ,
oh
sync(guild=discord.Object(guild_id_here))
this'll work
alright
and please use #bot-commands for testing stuff, lets keep the chat context full
what if i wanna make it global?
โ
still a error
new code and show ur imports
kk
dont specify the guild kwarg
is there an event to check when someone starts screen sharing?
if you now did import datetime you would have to change datetime.now to datetime.datetime.now
how to get user input
Code
datetime.datetime.now()+datetime.timedelta(days=365*5)
Import
from datetime import *
in discord.py
sync(discord.Object())?
i dont understand this
sync()
?
wrong reply, sorry
undefined name sync
?
yes sure py Member.voice gives you a VoiceState object, you can use
VoiceState.self_stream # to check streaming
VoiceState.self_video # for video
in voice_state_update event
in discord bot
string
self.tree.sync smh
How do you get red and green color in the ?
!d discord.ext.commands.Bot.wait_for @slate swan
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
bruh i already have that
But in my own bot
now it works but kinda weird
"```py\n text uwu\n```"
yes, and then i want tfo know how to do stuff with the message
.
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
@slate swan
i dont have the money to buy anything else okay?
bcs someone gave me a link to an example and thats what it showed
it was discord.Client in example if you forgot
and you changed it to discord.Bot
then someone asked you to use commands.Bot
ok so now what?
examples/app_commands/basic.py lines 10 to 12
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)```
remove that command tree ig, yerl can guide you better with this
i haven't really touched the library in months
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
async def setup_hook(self):
await self.tree.sync()
```?
@slate swan when i do the time stamp:
arg1 = datetime.datetime.now().strftime("%y %b %d")
arg2 = datetime.datetime.now() + datetime.timedelta(days=365*5)
first one gives 22-June-01 and the 2nd
2027-05-31 20:19:22:814542 but i want the to be the same
well they are 2 different objects don't expect them to be equal
yoy can either compare the datetimes of both or the strftime str kf both
but i want the to be just day month year and not year day month hour minute second and millisecon
okay the code runs fine but the commands still dont show up
strftime the second one too
Adding roles
So I have a Role Object called mROBJ and I want to add only mROBJ to the ctx.author how can I do that?
!d discord.Member.add_roles
in dms too?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
error can only concatenate str (not "datetime.timedelta") to str
when i used discord-py-slash-command package for them it worked immediately in dms
you used wrong syntax
subcommand not in
and if you arent new then...
what then?
bcs it doesnt
wrap the objects you add in a bracket and use the strftime on it
Adding roles
So I have a Role Object called mROBJ and I want to add only mROBJ to the ctx.author how can I do that?
!d discord.Member.add_roles
it is like this rn arg2 = datetime.datetime.now().strftime("%y %b %d") + datetime.timedelta(days=365*5)
POV: you have to restart the client
global slash commands do get registered in dms, if they don't for you, your bot hates you
spare few seconds to read what i just wrote pls ๐
ok switched to guild, how will i know if they load?
but it doesnt show up on discord, you cant use a slash command if it doesnt show on the slash command list
class MyBot(commands.Bot):
async def setup_hook(self):
await self.tree.sync(guild=discord.Object(981206560481083492))
```?
i don't understand it
I said the same thing 5 minutes ago...
uh
i am a kid who just learned to speak english
i understand almost nothing
i own the server
!e ```py
import datetime
print((datetime.datetime.now()+datetime.timedelta(days=365.25)).strftime("%B %y"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
June 23
best example i could give
import discord
from discord.ext import commands
import os
import asyncio
from discord import app_commands
bot = commands.Bot(command_prefix = "; ", intents = discord.Intents.all(), case_insensitive=True)
bot.remove_command("help")
MY_GUILD = discord.Object(id=981206560481083492)
@bot.event
async def on_ready():
print("Bot Status: ONLINE")
class MyBot(commands.Bot):
async def setup_hook(self):
await self.tree.sync(guild=discord.Object(981206560481083492))
@bot.tree.command()
async def test(interaction: discord.Interaction):
"""Test Command"""
await interaction.response.send_message(f'Testing')
async def main():
async with bot:
await bot.start(os.getenv("token"))
asyncio.run(main())
what if its a leap year.
the bot brooo
defined twice
once*
that still adds up to 365.25?
oh wait uhh nvm
ik someone was gonna ask that for sure thats why mentioned the .25 there explicitly
Idk why I'm just saying nonsensicle things rn
@slate swan thx so much
yw
sleep
you can always just overwrite the coroutine
wish I could, who'll make dinner ๐
but it would be better if you subclass the Bot class
yep yep
ok it runs fine but the command still does not appear in discord
Wait so when is the setup_hook function called?
What is like the ultimate guide for discordpy information and everything because I only find little snippets of information here and there
Or wiki
before any events are dispatched
import discord
from discord.ext import commands
import os
import asyncio
from discord import app_commands
class MyBot(commands.Bot):
async def setup_hook(self):
await self.tree.sync(guild=discord.Object(981206560481083492))
bot = MyBot(command_prefix="; ", intents=discord.Intents.all(), case_insensetive=True, help_command=None)
@bot.event
async def on_ready():
print("Bot Status: ONLINE")
@bot.tree.command()
async def test(interaction: discord.Interaction):
"""Test Command"""
await interaction.response.send_message(f'Testing')
async def main():
async with bot:
await bot.start(os.getenv("token"))
asyncio.run(main())
So like after on_ready or smth?
on_ready is an event
discord api is a REST api, you dont need to be ready to do that
@slate swan my code
Okay, guess I got some homework to do on REST APIs
!d discord.utils.format_dt is better
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
both of the properties return datetime.datetime object, so use the strftime method on it
joined_at.strftime(...)
dont you sync app commands with an endpoint why would a connection with the gateway matter in this case?
Uh, its been months since I have done bot deving
I haven't even read the new API docs on slash commands or how libs handle those
how can i get the length of an argument within a command? like in javascript you can use whatever.lenghtOf how do i do it in python
i think it goes the same way as for changing presence and sending messages?
i think so
ยฏ_(ใ)_/ยฏ
U need to be connected to the gateway (ws) to change presence
and the message thing?
no
Messages are sent via the HTTP API so u can send those
Reasons I don't care about it
it depends really but the worst case is just dispatching an event when self.ws is none
its not that bad its just not really recommended
no errors but it doesnt help
Well u can still send the HTTP Requests in on_ready. Worse case scenario: The request is gonna sent twice, but eh, no one cares (at least I don't)
which this can be fixed just by doing it on_connect lol
you need to format the datetime using .strftime(" a formatting string")
hm , the on_ready is called after the client connects to the webserver cause i used to connect to my prefix database in an on_ready event and used to receive errors that db is not connected whenever someone sent a message too quick after bot start
thats incorrect actually
In this article, you will learn to convert datetime object to its equivalent string in Python with the help of examples. For that, we can use strftime() method. Any object of date, time and datetime can call strftime() to get string from these objects.
on_ready gets dispatched on cache setup/population
andy back me up
Because Context type is a Generic, you can just do commands.Context[Any] as a temporary fix
Or you could use the Bot type, thatโll probably work. Since the TypeVar is BotT
on_ready in discord.py is 100% a library abstraction. The APIs READY is mapped to discord.pyโs on_connect
With discord.py, on_ready is just waiting for an asyncio.Event that waits for futures to complete, those corresponding to guild chunking
๐
hey how hard is it to code a discord bot? how much experience should somebody have before attempting
TLDR on_ready != Gateway connect; on_connect == Gateway connect
I feel like it was the wrong choice to make the names like this, but not a huge deal
discord/state.py line 516
async def _delay_ready(self) -> None:```
discord/state.py lines 585 to 586
self.dispatch('connect')
self._ready_task = asyncio.create_task(self._delay_ready())```
yep sure
what else did i say above ๐โโ๏ธ
If weโre gonna go technical, youโd receive HELLO first; but discord.py doesnโt expose that
Why doesnt this work?
the id must be an int and that function can be vulnerable to a NoneType error
describe doesnt work
No
within bot.load_extension("utility") how do i change this if the file is in a folder
How can i make a command that deletes a certain dump with the guild id in a json file
dont use json
use smth like sqlite
theyre made for databases
someone
pls help
"folder.file"
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
and use .send on this
Also you would want to defer the interaction
My bot is taking a long time to to start running code from async def on_message(message). I have checked the runtime of the message processing and command processing, both of which are under a second but when i time how long it takes for the bot to respond, its about 5 seconds which means that the bot takes about 3 seconds until it starts running code after it detects a message
If you put a print() as the first thing in on_mesage like this:
@bot.event
async def on_message(message):
print("Recieved new message")
...
Does that print instantaneously after sending a message in discord?
no, it takes about 5 seconds
i also have this:
Did you send a message instantly after you ran the bot?
Oh you have a print there I assume?
the bot sends that
And you sent a message after you saw that
Right, I'm asking did you wait until the bot was fully ready before sending the message?
yea
i print the client when its ready
i just sent a message after that
@client.event
async def on_ready():
print(client.user)
it's just taking a while to receive messages
I can tell, try turning on logging to see what's going on
How do i put multiple values into a library from one variable?
Can you specify?
Example
one = What im getting all my values from
for x in one:
test = x.name
library = [test]```
Is what i got at the moment, but test has multiple values (Words) that i want to be put into the library
Oh you want all of x.name to be into the library list?
Yes
one [...] # your stuff
library = [x.name for x in one]
but as words, bcuz at the moment it just does ['MYVALUE'] when printing it
its logged down the message at the correct time ish
Oh lemme try
But actually responding happens way later?
yea
Can I see your entire code?
but its not the code runtime because i log that
it's really long\
Alright, how about just the on_message?
that worked,
role names are being put into the library
how can i see if any of the role names if the library is in the authors roles?
everything is inside the on_message
because of intents
I am trying to write a program for my sell command in my economy bot so that when a user sells the item, I want to delete the json object from their inventory. For instance, if they sold one piece of bread and the item's amount equaled to 0, then it would just delete that whole object. Here's a screenshot:
id is just replaced for the actual user id, for security purposes.
Can someone help me with this?
would be faster with map
No it wouldnโt
Pretty sure maps are slower with lambdas
Probably set intersection
In your sell command add an if statement to check if inv[index]['amount'] is 0, if true; pop the item using it's index.
Ex: inv.pop(0) and finally re-write the file.
and even if you use attrgetter instead of a lambda it will still be slower here
Are you hosting on replit?
Okay, any awaits inside loops?
Anything like this:
for ...:
await ...
Or
while ...:
await ...
Can I see it?
Is that in a command?
And did you get rate limited when running that command?
Strange, can you post the full traceback?
Are you hosting this bot at all? Or is this self hosted
Mmm, it could totally be that then, depends on the service
If itโs free youโll most likely be in a shared container. So the IP caveat applies
Ah yeah I should've mentioned that
Ok, but considering pterodactyl, Iโm almost 100% sure this is all in a shared container
If you have contact with your host provider you should ask if itโs a private or shared container
Thatโll let you know for real
Or, unless they lie
#discord-bot-hosting
In the pins^
Hey im trying to make a discord bot loop through all the members in a server and check to see if they sent a message if so it prints User has sent a message and if not it prints user did not send a message. Can someone help
If you're already paying for your current one, your options are much more varied
That isn't possible
Welp, must've been a weird method then cuz as far as I know it isn't possible
You can
Maybe just create_task for the first bot, await the 2nd await bot.start()
Or Threading
Yea you use create_task
That's probably the better way yeah
Hey im trying to make a discord bot loop through all the members in a server and check to see if they sent a message if so it prints User has sent a message and if not it prints user did not send a message. Can someone help
I wouldnโt thread here
Because discord.py uses Locks and what not
Which isnโt thread safe
And keep in mind the main meat and bones of the ratelimit handling system is the Lock
Since discord.py updated and u can't get messages older than (idk how old), I don't think u can do this properly.
damn
The real question here is do you really want to run multiple bots in the same file
(hint: the answer is no)
x["container"]["US"], index it, no need for a for loop
thanks you so much
Dumb question, is there a way to get the key by the value in a dict as well?
No
I've always wondered about it and never saw something like this in basics years ago
There's no built-in way but you can, iter through dict.items() and check if value equals to what you're expecting then just return the key
Anyone know how to get pass this issue?
Im trying to put my bot on the cloud so I can have it run but the tutorial im following has me doin something with github but its having an error working
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='Currency Help', description='Displays all of the currency commands', emoji=''),
discord.SelectOption(label='Moderation Help', description='Displays all of the moderation commands', emoji=''),
discord.SelectOption(label='Utility Help', description='Displays all of the utility commands', emoji=''),
]
super().__init__(placeholder='Select Help Commands', min_values=1, max_values=1, options=options)
embed1 = discord.Embed(....)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}', ephemeral=True)```
im trying to send a corresponding embed instead of `Your favourite colour is {self.values[0]}`, how could i do that?
this is #discord-bots so i am significantly less intelligent than you, so can you please explain in a different way?
Is the "discord" not outdated?
its not
It seems that it no longer works and you need to use nextcord
no
Do you know how to create and send embeds?
or you mean for the dropdown
Ok...
yes
Ot isn't
Well create one and pass it as a argument in your send_message command
Just as how you do interaction.send(embed=Embed)
ok but i want a different embed per different select option
If so then simply create the embed in the callback and add their selected choice as an embed field
Lol, just send embed and then something else
The callback function is called when the person selected something. Just embed = Embed(), embed.add_field(name=Foo,value=bar)
Then .send(embed=embed)
how would i send the embed that corresponds to the select option
Oh I'm a fool
channel.send(embed=yourEmbed, somethingElse=...) maybe so?
its a coroutine!
I'm forgot
Does it work?
yes
That's right. I'm sorry, I confused the libs. This won't work on nextcord :)
ye nextcord is different
only nextcord v3 is going to be different
nextcords implementation on slash commands is different compared to dpy but similar to disnake
I'm not for PC, I don't remember the nextcord version
v3 is not even usable yet so...
"is going to be different"
soon ig when epic actually does something with it๐
Is it possible to swear here?
is epic the core dev of nextcord?
the owner yes
yes but you cant aim it at anyone and dont offend anyone and keep it controlled thats really all
um yeah but keeping the chats civil is the priority
OK, then I'll tell you the "Don't fuck with my brain"
Whu do you need the source code?
its not like I'll migrate from hikari to nextcord again
Why*
because its not on pypi and the only real way to test it is copying the repo lol
you can talk more about it to vco because hes a core dev
Ah, I didn't know
Probably
nvm thats a stupid question, how do we even define major
ive only seen a list of api wrappers which bluenix made which isnt only forks
Maybe they can be sorted into forks?
probably only the most popular ones like disnake and nextcord
You're a genius, first you say that nextcord is different from discord.py and then you say they're the same. Or is it that I have such a crooked translator
pycord ๐
12 votes and 29 comments so far on Reddit
i saw this and couldn't resist looking into the comments
nextcord v2 is still a fork of dpy
nextcord v3 isnt ;))
Oh, well
โ ๏ธ
why are you on reddit sarthak๐ ๐ณ
uh someone sent this link in hikari and apparently i just opened it
code is poorly written ๐
are you sure shawty๐ณ ๐
Is this the first time I've heard of PyCord?
yes very much
you can un-hear it
its one of the popular forks
0_0
๐ฉ
I would take what's on reddit with a pinch of salt
Maybe I forgot something. I haven't coded for python for more than half a year
You're a helper 0_0
a discussion between pycord is the best fork vs pycord code bad ppl
I could pull a Rin revival out of my ass and have better implementation than py cord
Yeah, like a long time ago lol
andy chill jesus christ
shush you never completed it
๐
I believe it too
Havenโt committed a single implementation but it exists I assure you
but i like it more than pycord's existing stage :kek:
๐
Can you see deleted messages?
get it done ๐
sarthak how are you using emojis from another server but you dont have nitro?
like i dont see your badge ๐ญ
thats global emojis, andy would know
I need to find motivation for Rin, after all Iโm a one man team
Only moderators and up can see that
Indeed ๐คจ
๐ณ
thats a thing from before when nitro existed
Did.. someone delete a message here?
I understand, there's just one joke here)
and how do you still have access to it?
)))))))))
ive actually never heard of them
We're breaking the 4th wall now are we
I remember joining hella GW emoji servers cause I didnโt want to buy nitro
I don't even know who it could be
well they still work somehow
4th wall? What?
Dunno, something like "I see you mods" and deleting it
and how do you use them do they just work like nitro?
yep, there are only 9-10 of them on me though
so its like binded to your account?
no you just join the server and use the allowed global emojis normally
what server like servers that had them before๐คจ
interesting
so anyone can access them still?
yea that was a big one, and the one i sent just now was one from "Love gaming" thats a smol Server idk how they have it
well i just did~
After that, everyone fell silent... Lol

XyiloCordFlashbaks
Huh
After that, everyone fell silent... Lol
Okay, I'm going to sleep, bye for everyone
Do I need to include a json file when using heroku
becuase it says "No default language could be detected for this app."
I dont know if Im missing somethin or waht
yes
oh my fault didnt realize it was a different channel
Nah it's just a thread
Does anyone know how to create embed with this:
{content: This is the content part}{embed}{title: This is the embed title}$v{description: This is an embed description}$v{url: https://discord.gg}$v{author: Author Name && https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024 && https://discord.gg}$v{field: This is the field title && This is the field description && true}$v{thumbnail: https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024}$v{image: https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024}$v{footer: This is the footer && https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024}$v{color: #0062ff}$v{button: This is a button && https://discord.gg}
The output is this:
https://tokyotokyotokyotokyo.tokyo/โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
(it's basically an embed builder so people can do custom embeds for certain things)
@sick birch i found that the firebase realtime databases are json...
Yes, most NoSQL databases resemble JSON in some way or another
ok so is there sql databases you reccomend that are hosted in the cloud?
!d discord.Embed
AWS RDBMS
ok so can you help me understand how much usage is free?
It's kind of complex
You'll probably want to use their calculator to roughly estimate cost
which database would you reccomend?
PostgreSQL, used heavily in the industry. Standard & robust
there is a lot in the list when i typed database
Amazon RDS for PostgreSQL this?
I actually have no idea what AWS RDBMS uses behind the scenes :p
Actually looks like I'm confusing myself
RDBMS is the management system, RDS is the actual database service
but yes
the free dosent cover it lol
whats the one thats hosted by the devs of opera
Not sure, never heard of it
it was oracle
Can bots send code blocks?
Yes, they can
yes
What are some good ways to grow my bot and promote it? I know there are people that might want my bot and I know the target audience. Just not sure how to get to people easily...
discord bot list /top gg contact some big server mods many ways there
good morning!!
I'm already on top.gg
yeah get votes
uhhh @sick birch. should i just self host my database? the mess that orcale has me going though has lost me
I got some friends to put up like 30 but they go away after a few days
