#discord-bots
1 messages · Page 1040 of 1
ctx.message.created_at.timestamp()```
using this i get time 5 hours ago how i get the time that is now
use datetime.datetime.utcnow()
that gives you the UTC datetime, as the name suggests
i want it like <t:73777377:R>
!d datetime.datetime.astimezone
datetime.astimezone(tz=None)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object with new [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") attribute *tz*, adjusting the date and time data so the result is the same UTC time as *self*, but in *tz*’s local time.
If provided, *tz* must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and its [`utcoffset()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcoffset "datetime.datetime.utcoffset") and [`dst()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.dst "datetime.datetime.dst") methods must not return `None`. If *self* is naive, it is presumed to represent time in the system timezone.
If called without arguments (or with `tz=None`) the system local timezone is assumed for the target timezone. The `.tzinfo` attribute of the converted datetime instance will be set to an instance of [`timezone`](https://docs.python.org/3/library/datetime.html#datetime.timezone "datetime.timezone") with the zone name and offset obtained from the OS.
enter your timezone for the tz arg
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
yea that too, but just to make sure it returns my timezone even when hosted on a vps from another location, i prefer using astimezone
on_member_leave or on_member_remove
leave doesn't exists
remove?
it does
hehe
how to add server icon in embed author ?
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.
can i add buttons in my bot's custom rich presence?
no
;aw;
!ping
You are not allowed to use that command here. Please use the #bot-commands channel instead.
huh?
Wtf?
i agree
wdym find the arguments for a command?
like
@bot.command()
async def command(ctx, arg1):
await ctx.send(arg1)
and it would say something like
command name: command, arguments: arg1
i think there's something like <> for required and [] for optional?
i think most ides show u the arguments already
no, to send the arguments in discord 
help command?
bruh
for bots?
I'm coding my own help command
if thats what ur talking about
wym
explain
Just do
uhm all commands are an instance of discord.ext.commands.Command class, if you check the doc you can get all those parameters
to get all the commands of your bot you can use discord.ext.commands.Bot.commands
alr thanks
after surfing the docs I found my answer, thanks a lot!
np
i want to host my bot on heroku but this comes up;
I watched a youtube tutorial and it didnt help me
Yes, in the help command
Heroku isn't the best option for hosting a Discord bot. Consider using a cheap hosting service or even a free one.
is anybody selling discord verified bot dm me@molten umbra give space after if
...
Besides the fact KeyError said we help with discord related code not Heroku.
Hey anyone want to help me build a simple discord bot. I have no experience. It is a small bot that orders something through an API
hi guys, uhm sorta new and i followed a guide on youtube. I dont understand the problem here can anyone explain it? Thanks a lot
File "main.py", line 15
await message.channel.send('sup')
^
SyntaxError: 'await' outside function
^(the error)
The problem is that it seems that you don't know python 
duhh give space after if
it's ok we should always encourage
i learned a bit but literally very little
!indention
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
i can understand how much little
indentation in python is important
@molten umbragive space after if
yesh
from discord.ui import buttons
Ik this is a dumb question
PEP8 suggests tabs (4 spaces) 
Most modern forks have those already implemented.
k
Any docs link?
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
yesh
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
how to install discord.py 2.0?
py -m pip install git+https://github.com/Rapptz/discord.py
you must have git installed
thx
;
alr thx that worked.
Like any normal developer 
ok
There are more amateurs here than devs 
lol
Depends on the environment
not in option
;aw;
!pypi aiosonic
Can someone help me make a small simple discord bot with only one function or ordering a service through a api
what do u need kid+_+
which service
ill dm you

ok
I'd go with aiohttp.
hmm
Def not aiosonic since that doesn't get updated as often.
you studied aiosonic before give the answer? xD
One liners: no
though aiosonic is 101%faster than other apis still aiohttp fafstest in calling apis fast one after another
yesh little bit
aiosonic is a library, not an API
it requires you some skills to convert some operation into 1 line 
People here don't have those skills
i have tried each of the 3 and aiohttp is most effective so i recommend to use aiohttp in ur antinuke bots
: )
hey @light violet can you look at my dms
ok
pls send dpy 2.0 docs
;aw;
alsmost same with added features
idk the new docs
why would it be faster?
you forgot the protocol😭
didn't know that discord don't recognize urls without protocol
well no if you try to send a link in whatsapp for example the protocol is not required
yeah but not in discord lol
that sucks tho 🏌️♀️
For someone like me who often types . instead of space
well you have to type a domain after the . to make it a link 
Hey can you look at my DMs please
What project are you seeking help with? Its usually better to ask your question in-channel so more people can help.
He asked me to make a bot lel
!rule 6
That includes in the DMs of server members
I did not 
I have no experience with discord bots and little with python and need help to create a discord bot that orders things through a API that I have.
That requires some experience tho, start by reading documentation or watching some course
Alrighty. Well you could work out how to make the API call and then add that to a simple bot. What API are you using?
No, I don't provide help through DMs. Please ask your question in one of the available help channels (See #❓|how-to-get-help ). The main reason is that by asking your question in public, everyone can contribute to the answer or benefit from it. Also, as we're a fairly large server (300k+ members), it prevents our staff from getting flooded with DM requests for help.
Yes but it's not like we can provide the entire code of a project 
We are here to help the others, not to develop their ideas
Where can I find someone that could maybe develop it for free
I cant afford to pay someone
We can help you learn how to do it, but won't do it for you
just ask here?
I need it quickly and it will take a lot longer for me to learn it then build it..
nevermind though
Alrighty. If you want to learn how to do it, we will be here
self is meant to be used only inside classes
me who names it myself
Is this how you add reactions ? and what would go into the ()
await ctx.add_reaction()
upto you
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is “synthetic”
and does not actually exist. Therefore, the ID on it is invalid similar
to ephemeral messages.
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji")...
it should always be named self🧍
🚶♂️ true, but naming it "myself" wont make the interpreter shout at you
😭
apparently, pylance wont bother
best param naming award goes to you
potatoes
embed = discord.Embed(title="a string", text="a string")
message.channel.send(embed=embed)
create the object and then send it, will vary depending on what library you're using etc.
thanks
also what do i do when it says intents unfilled?
you're getting that for sending an embed?
client = discord.Client()
i did this and it said unexpected argument on the text part
ah yes fixed
thank you
I’m making a discord bot for my school final project and one of the requirements is a loop… I could be unoriginal and do a spam ping command but I want to be original. What type of command could I do that uses a loop
A loop? for loop? while loop?
Any kind of loop
use tasks loop then.
Wdym by loop?
Don't use spam bots
Against tos
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
watch them delete bot
Lol
😂
@bot.event
async def on_message_edit(message):
with open("logchannel.json", "r") as f:
cfg = json.load(f)
logchannel = cfg[str(message.guild.id)]
embed = discord.Embed(title="Mohameme Logs", description="Logs message", colour=discord.Colour.random())
embed.set_footer(text="Mohameme bot")
await message.guild.get_channel(logchannel).send(embed=embed)```
I'll just go away from here, I'm really having bad mood swings today :awkward:
Another one
!d discord.on_message_edit
discord.on_message_edit(before, after)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") receives an update event. If the message is not found
in the internal message cache, then these events will not be called.
Messages might not be in cache if the message is too old
or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter
or use the [`on_raw_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_edit "discord.on_raw_message_edit") event instead...
@bot.event
async def on_message_edit(before: Message, after: Message):
...
ty
i thought it worked like other events like msg delete
just a for loop? make a very simple tarot pull command, loop through list of card names and pull 3. Should be some decent examples online
my idea ur welcome
he wants his bot to spam messages so a while loop is better
Nuke prob
Ayo
should delete this
How can I make my bot do this for each message sent? ```py
q = str(ctx.message.content)
answer = requests.get({API}+{q})
print(answer['cnt'])```because ```py
@client.command()
async def on_message(ctx):
q = str(ctx.message.content)
answer = requests.get({API}+{q})
await ctx.send(answer['cnt'])
because i uesd to get an error
the attribute returns a string
ok
!d discord.Message.content
The actual contents of the message.
and the error is probably an attribute error
because youre trying to do Message.message.content
its on message so it doesnt have context
and its message.channel.send
as message doesnt have such a method
OK
@slate swan u do know that u can combine all those messages in a single message, right?
👆 It breaks ToS
API+q
never knew
🥲
mb
How can I make it so that every time a message get's sent in the server, the bot sends it to the API and sends the API response to the chat?
should be a command
because if someone sends a simple hi the api is going to get a request
and if the api doesn't have a ratelimit thats fine but if it does thats kinda a problem and you should never spam an api or make unnecessary calls
use some kind of regex/logic to make sure when to make api calls
nope
or can someone suggest this about me to be added in the api
bots dont have access to the about me section
@client.event
async def on_raw_reaction_add(reaction):
user_id = reaction.user_id
await auto_lu_msg.edit(content=f"{auto_lu_msg.content}\n{discord.Guild.get_member(user_id)}")
Error:
- File "G:\FreezeBot\gather.py", line 79, in on_raw_reaction_add
- await auto_lu_msg_id_msg.edit(content=f"{auto_lu_msg_id_msg.content}\n{discord.Guild.get_member(user_id)}")
- TypeError: Guild.get_member() missing 1 required positional argument: 'user_id'
whats wrong with this 🤔
should be using an instance of a guild
reaction does not have an author/user
Ah I forgot it has users
Nvm I just saw he has access to the id
how do I create a slash command?
@commands.slash_command()``` decorator instead of `@bot.command()` and you're good
oh this is disnake
/discord
im using discord.py 
discord.py got a slash_command decorator?
I dont think so
no.
lmao
We use app commands
property owner```
The member that owns the guild.
I guess not
sooo
maybe I’m just bad
Python bot hates app commands
discord.app_commands.app_command
I will self diagnose myself with skill issue
iirc
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=...)```
Creates an application command from a regular function.
Ah
its a client.command thing no?
app_commands is just a folder
the namespace*
Just like ext
What about command tree? I think that was included
app_commands.CommandTree
Ah yeah
app_commands?
Yea
i always called it a folder, cause it is what it is :/
Hahaha but in C# its like
namespace Name{}
Python just treats the folders as namespaces
app_commands.CommandTree? man Im new to this
Yeah 2.0
Yea haha
There are a few examples in the repo u might wanna look at those
discord.py uses CommandTree s to store application commands
so theres no other way?
nope~
oof
if you use commands.Bot, a commandtree is automatically initalised ( from what i see in source )
Why would you need len for that
you know what len does right?
counts the lenght?
Then it’s probably in your best interest to learn what it does before using it
Right, a guild can have one owner
so it counts 1 
Not like guild.owner can return an iterable anyway
Well no
It’d count the letters in the name
oo
Actually no I don’t think so
Since it’s a member object
Don’t know if discord.Member implements the len dunder
Yes
you would have to iterate thru all bot.guilds and use the .owner property on them
💀 would be a dumb move.
why iterate when list comprehension exists? 
it returns a list
why iterate through a list to return another list of the same elements
for someone who doesnt know what len means, i dont want to make things complicated
oh btw how do you run a bot again after changing/updating the code?
If you use extensions you can hot reload it
you would have to do that manually, though there are some "save and run" extensions for most ides/editors
If not you’ll have to kill the script and run it again
If I'm using 2.0 am I am I required to use / command instead of regular commands?
or cogs, as robin said
You are not
....doesnt a list comp also iterate.....
Extensions, there exists a difference
I dont think I have an extension
Interesting because since I switched nothing works and I get no errors
That’s probably something wrong with your code
message_content intents?
Do you have any error handlers?
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.
!e
lst = ['a', 'b', 'c', 'd']
print("".join([i for i in lst]))
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
abcd
i don't see where the problem is 
u dont need the list....
bro
just ''.join(lst)
Just use “”.join(lst)
yeah it was to show them how to convert to a string a list comprehension 
and i see no reason why the extra list comp if str.join accepts an iterable
so you still couldve use the generator without casting it to a list
but theres already a list so no point in that
Enabled
in the code too?
Not every command has one
Yep
intents = discord.Intents.default()
intents.members = True # Subscribe to the privileged members intent.
bot = commands.Bot(command_prefix='.',
status=discord.Status.dnd,
intents=intents,
activity=discord.Game('beach-hosting.com'))```
see if you error handlers are stopping your errors from raising
thats not message_content intent
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages
which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client...
Make sure it’s also enabled on the dashboard
They are
So I need to do message_context=True
@sly hamlet What bot did you make? I'm curious
It's a general custom Discord bot for my server

nice choice 👌
discord-py-interactions
weird
How did a bot for your own server get verified?
I've made more than one bought my guy I've made a public bought and I make custom ones
bought?
Right..👌
Auto-correct probably
might be autocorrecting bot to it
Bot's don't have CPUs, your host does
they probably mean cpu usage of the process on the host?
if so, check out the psutil package
yeah you can use psutil
@distant river, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
Hi guys, I'm trying to send all of this images in one embed. Currently, I'm sending one message after one message. Does anyone has a solution to this? Here is my code:
@client.command()
async def multiple_charts(ctx, s1, e1):
embed = discord.Embed(
title=f"6 Charts from date {s1} to {e1}", color=0x00ff00
)
file = []
for ticker in tickers:
VisualizeData(ticker, s1, e1, "gamma", theme).graph_data(zero_gamma=True)
file.append(discord.File(f"{ticker}.png"))
embed.set_image(url=f"attachment://{ticker}.png")
# spx = file[0]
await ctx.send(embed=embed)
await ctx.send(file=file[0])
await ctx.send(file=file[1])
await ctx.send(file=file[2])
await ctx.send(file=file[3])
await ctx.send(file=file[4])
await ctx.send(file=file[5])
aww
Wording is important, one can misunderstand what something is if the person didn't word it correctly and I'm just correcting them
ok, this is what I thought too. So do you think webhook is a good library to attach multiple pictures in one embed?
webhook library? ignoring discord limitations?
oh, it can send multiple images in one message but can't embed. I see
right
I do like to embed multiple images in one message though 😄
and you can send multiple images with the files kwarg
Install it -> import it -> use it ```py
import psutil
percent = psutil.cpu_count() # I can't remember if this is the correct method or not, but tias
What explains my on_message_delete logs only responding for messages that got sent and deleted after launching the bot
Ignoring exception in view <Counter timeout=180.0 children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Close Ticket' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\culan\Desktop\beach hosting\beach hosting.py", line 641, in count
channel_id = Interaction.channel.id
AttributeError: 'CachedSlotProperty' object has no attribute 'id'``` why do i get this?
the heck is a cacheslotproperty
idk
what library are you using?
You need an instance of Interaction, then use channel.id
discord.py 2.0
normally....
Up to you, idk
So it needs a message to be sent first?
Nakime you have to start being more self-learning
No, if it's in a button you can use interaction (or whatever your second parameter is called)
I'm confused what I'm doing wrong
Show me the top part of the button
@discord.ui.button(label='Close Ticket', style=discord.ButtonStyle.red)
async def count(self, button: discord.ui.Button, interaction: discord.Interaction):
em = discord.Embed(color=0x1014C1,
description=(f"This ticket will close in 10 seconds."))
await interaction.response.send_message(embed=em)
await asyncio.sleep(10)
await interaction.channel.delete()
with open("data.json") as f:
data = json.load(f)
ticket_number = int(data["ticket-counter"])
channel = bot.get_channel(793569113708036106)
color = discord.Color.red()
em = discord.Embed(color=color, title="Ticket Closed ", description=(f"{interaction.user} closed a ticket\n **Ticket #**\n {ticket_number}"))
await channel.send(embed=em)
channel_id = Interaction.channel.id
index = data["ticket-channel-ids"].index(channel_id)
del data["ticket-channel-ids"][index]
with open('data.json', 'w') as f:
json.dump(data, f) ```
☝️
I feel like I could make a verified bot
@slate swan 😔 I apologize for the random ping but, is it ideal to create inside an extension (and where should I start it) or in the main bot file?
he'll never forgive u for that ping
create < insert create what object here> inside an...
and im completely foine with pings
uhhhh a task, Im going insane
you just ruined his job interview at google with that ping
i'd prefer using a plugin
hm, where would I start the task then? while loading the plugin?
tasks have a auto_start kwarg
☝️
oh, I see
alsooo, you gotta tasks.load(bot) (anywhere) to make those tasks work
just stop, what do you even have with me, every time I write something, you got something to comment over 😭
you can task_function.start() in the load function too
yep, already saw that in the docs
I'm an idiot
thanke a lot
yw
We all are sometimes
this aint working for some reason
dont say obvious things
any one know why?
Don't be rude.
ahem ahem
Error?

?
look who's saying that 😔
meh me 😔
me, meh
u wanted to see error?
Slash command names can't have underscores
you have some unwanted character in the command name
you can~
also, shouldn't it be components and not Components
Really?
thats the sub command nvm its valid
it's commands.Bot
Oh my
Which library are you using?
what
hmm
turns out that is pycord with discord.Bot
like what?
What ryuga said lol, groups can't have them
my confusion isn't braining
Hello 👋 Is it possible to split a command group across cogs? Or rather, if there is a command group in an existing cog, is it possible to add sub-commands in a separate cog (without modifying or monkey-patching the original cog)?
how about importing the group
or cog
or getting it through bot.get_cog
cuz then, sure, you only need the group instance to make a sub command for it
You mean to monkey-patch it?
I don't know what you mean by monkey-patch
send doesn't have kwarg called Component read the error 
it says it does in the api reference
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
Oh, I mean externally modifying the class/instance. I'd like to not assume to much about how and in what order the cogs/extensions are initialised.
@boreal ravine @paper sluice comments?
im using discord-py-interactions
ya mb
😭 whats a maybe i just made a command to prove that lmao
the cogs are stored in the bot (I think in the cache), from which get_ gets all its information from
Any game recommendations like we have akinator pypi
i just pulled out the src
showing code will let you have better help
I did earlier
so you would just get the instance of the cog, and I'm not sure if bot.get_command can get a group
but might be
I'm gonna look
Using a decorator or?
It’s easier if you’re just using the method calls
it does
!d discord.ext.commands.Bot.get_command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list
of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get
the subcommand `bar` of the group command `foo`. If a
subcommand is not found then `None` is returned just as usual...
it seems to
Erm, so I was hoping if I define the same group in two cogs, with different sub-commands, then I load both cogs, that the sub-commands might be merged together somehow 😄 But that's probably wishful thinking.
I think one would be overwritten
Doubtful
it should raise an error saying command already exists
oh
Ah right ; - ;
I'm throwing
But your question of multiple subcommands spread throughout cogs should be possible
button = interactions.Button(
style=interactions.ButtonStyle.PRIMARY,
label="hello world!",
custom_id="hello"
)
@bot.command(
name="button_test",
description="This is the first command I made!",
scope=GUILD,
)
async def button_test(ctx):
await ctx.send("testing", components=button)
@bot.component("hello")
async def button_response(ctx):
await ctx.send("You clicked the Button :O", ephemeral=True)
bot.start()
hey, I'm kinda new to python, how do I install this API for my discord bot? https://github.com/pybricks/pybricks-api I'm trying to do it for vscode
User API and documentation for Pybricks MicroPython - GitHub - pybricks/pybricks-api: User API and documentation for Pybricks MicroPython
Oh right
The context is adding another sub-command to a command group on ModMail using a plugin (which is just a cog essentially).
You may have to go into the existing code to change things up a bit unfortunately
It’s not very plug and play
Right I see. Erm, I'll probably just make it a top level command then.
hello? anyone
Before you do anything python related please learn the language first, and you don't install APIs, you use them
Thanks 
If you’ve a question, go ahead and ask it
Make a request to it
idek wht an API is ;-;
this doesnt work, anyone know why?
Hey 👋 An API is just a way for two programs/systems to talk to each other. What would you like to achieve with this API?
^
make a discord bot that communicates with a lego mindstorms brick
Oh right hmm 🤔
I'd break the problem down into two tasks:
- Figure out how to communicate with the Mindstorms brick from a python program running on a computer.
- Integrate it into a Discord bot.
For the first task, you may get better help in #microcontrollers
Point proven I guess
Alright, post a question in #microcontrollers. Provide details about what you're trying to achieve, what kind of communication you would like, what the brick will do, etc.
Hello I’m making a discord bot that gives role on your status what would be best way to go about it
!d discord.ext.commands.Bot.event
@event```
A decorator that registers an event to listen to.
You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events).
The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)"), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") is raised.
Example...
There is an event, which is on_member_update (iirc)
!d discord.ext.commands.Bot.listen better
@listen(name=None)```
A decorator that registers another function as an external
event listener. Basically this allows you to listen to multiple
events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
yo, does anyone have any suggestions for what i should put as the playing status for my bot
the prefix?🙆🏾♂️

btw do you have a suggestion for the prefix? currently its a comma, i'm trying to be unique so it doesn't get mixed up w/ other bots
Just make slash commands
i did, im using both
I would recommend } nobody uses it
I mean there are so many bots like billions (replace the B with m) so i think you cant have an "unique" prefix🌚
does anyone use "#"
Yes
me with my dict comps💪
Does tht make sense? To yall
obviously another bot will have the same prefix, but its not like servers have a billion bots as well
Just make prefix customisation why not
^
i tried but it would reset when i update the code and change for everyone using the bot
Json moment
yeah i will im just lazy ngl
Use mongodb its really simple
it looks like "json" doe
ill just watch a tutorial for custom prefixes, i haven't made a command like that yet
Me neither
how do people grow discord bots to reach 100+ servers?
i feel like im wasting my time if the bot doesn't reach many servers
Can someone develop a bot for me, there is only really 1 command I need for it, I have little to no experience or knowledge. Please DM me if you have some spare time to develop it with me
advertising I think, or creating and joining it to 100 servers haha
what command is that
its slightly hard to explain and will come out with a lot of waffle so can I DM you
okay
adding it on top.gg and other bot lists would be helpful for growth, other than that make sure to add the "Add to server" button on your bot's profile, sometimes people just want to invite your bot but are too lzay to search for its invite url somewhere so yea
the only thing is i feel that people won't add an unverified bot if another verified bot serves the same purpose :/
maybe small communities won't think too much?
from what i have seen, people add random bots to like test or try them too, even if its a small bot ( i log some basic information like server name, id, owner and member counts ) for my bot
from the data i get it seems like people causally add new bots
hmm ok, my goal rn is to get it verified
i started developing it yesterday lol, just used saved code from my other bot and i'm adding slash commands and all to it
good luck with that, will suggest to keep a track on what servers you bot get added in because adding the bot to fake servers may lead to a "Inorganic growth" report
cool
ik, ill just add it to a support server for the bot and try to advertise it
also, should i check the administrator permission or manually add other permissions? (its a moderation bot that can ban, kick, mute, etc)
best to keep the admin perms optional
okay
because its a permissions a bot never really needs
but it still needs to be able to ban and all, its a mod bot
there are kick and ban permissions
ik
you can ask for them :D
ill remove manage server and the unnessacary ones then
yea~
go to #help-rice
code?
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
you tried converting the response from the first wait_for to a channel..
Make a feature that stands out I have made 2 bots and they both got verified in a week from being in 120 servers
fr?
do you have a suggestion for a unique feature
kinda hard question
bots are kinda limited to unique features
like its rare to see unique features and if you make one it eventually gets popular and its not unique anymore
i kinda stopped making bots because of this reason it gets boring
everyone stops making bots after a time
unless you own one of the most popular ones
2 bots 1st one verified in a week with 130 servers 2nd bot in 3 days 250 servers
I deleted it
bruh why
I couldn’t pay for hosting not time for updates ect
just use uptimerobot, it's free
Bro I wasn’t hosting on replit
oh
do you think replit would handle a bot with 250 servers
Fr 💀
repl is a ridiculous host
@bot.event
async def on_member_update(before, after):
if after.bot == True:
return
if before.activities == after.activities:
return
userHasActivity = False
for activity in after.activities:
if isinstance(activity, discord.CustomActivity):
if str(activity) == "test" :
userHasActivity = True
if userHasActivity:
await after.add_roles([974367821708550184])
else:
await after.remove_roles([974367821708550184])``` it wont give roles on status
Couldn’t agree more
If your hosting a test bot it’s ok
activity.name gives you the activity name. check test in that
Example?
I’ve never used user event before
how can i elaborate activity.name?
Fair enough 💀
members & presences intents?
Yup
is my bot approved yet
no
What does it even do?
The best host is your own server, if you have one 
what platform could handle a bot with 250 servers
That’s common sense
every host you pay for
Paid hosting
why do you need to use a platform?
okay
^ a vps would be preferred
a free google cloud/aws tier would be enough too
provided that it needs a credit card and the free trial period is one year
amazon web server micro currently handles my bot that's in 850 servers with around 13ms ping for free
the what
yea
Amazon web server
I’ve heard of it
Didn’t know if was good tbh
anything's better than replit
cannot recommend enough, there's a reason why amazon is at the top when it comes to hosting
although i'd prefer more competition
because they dont pay their employees enough they can spend more money on your behalf on servers
From customers pov it’s a W
is sparked host good? the prices are low as hell
Specs are really bad also don’t go for “bot hosting” search a vps
k
there are better ones, and cheaper too
cheaper than $2 a month?
lets move on to #965291480992321536
k
async def on_member_update(ctx):
if ctx.author.activities == "test" :
userHasActivity = True
if userHasActivity:
await after.add_roles([974367821708550184])
else:
await after.remove_roles([974367821708550184])
``` it doesn’t give role on status
yeah the activities list isn't gonna be equal to a string
and add_roles and remove_roles don't take lists
ikr
its not even a host
I said it's not a good host as in it's not good to use it for a host
not a good host
so its a host?
bro
lol
facts
wanna know why?
yes
alright, now let's start with the first things, alright?
first thing you'll notice: on_raw_reaction_add has a different argument than the one you named here
You don't edit discord.Embed objects, you edit the message they're in
waitt
i see what i did wrong, i should have made the await ctx.send in a variable and edited that
im stupid
No prob, it happens
Why do I get this error?
discord.errors.Forbidden: 403 Forbidden (error code: 20012): You are not authorized to perform this action on this application
Im trying to implement slash commands on an old bot
That has regular commands
Im just trying to sync my commands
im using discord.py 2.0
#DISCORD & ASYNCIO IMPORTS
import discord
from discord.ext import commands
import aiohttp
#OTHER IMPORTS
import os
from dotenv import load_dotenv
class client(commands.Bot):
def __init__(self):
super().__init__(
command_prefix='.',
intents = discord.Intents.default(),
application_id = 772489968823828490)
self.synced = False
async def setup_hook(self) -> None:
self.session = aiohttp.ClientSession()
for ext in os.listdir('./cogs'):
if ext.endswith("py"):
await self.load_extension(f'cogs.{ext[:-3]}')
await cltree.sync(guild = discord.Object(id=770698123915165747))
async def on_ready(self):
await self.wait_until_ready()
print(f"Logged in as {self.user}")
if not self.synced:
await cltree.sync(guild = discord.Object(id=770698123915165747))
self.synced = True
aclient = client()
cltree = aclient.tree
load_dotenv()
aclient.run(os.getenv("TOKEN"))
My code
It works just fine on another bot
I wouldn't sync the commands in on_Ready
It's generally discouraged to do any API calls in on_ready, the docs discuss why
as to why your syncing isn't doing what you expect it to: I'm only using 1.7.3 features, I can't say
Why does it not work?
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
but what did i do wrong then? I have the intent enabled == Fixed it
I’ve seen some commands that can execute psql Cmds, get what they ask for and send it, like getting everything in a table and it would send it to a channel. It’s like it’s running it in the terminal, getting the response then sending it to a channel, how could I create this?
So, now it works?
@commands.Cog.listener()
async def on_command(self, ctx):
results = collection_cmd.find_one({"guild_id": ctx.guild.id})
if results is None:
pass
elif results is not None and results["disabled"] is not None:
for x in results["disabled"]:
print(x)
print(ctx.command)
if str(x) == str(ctx.command):
break
hello im coding a disable command
im checking if a disabled command gets called in the on_command event it works but how can i prevent the command from getting sent, when i break or send a message it sends it after the command
so like after the for loop?
Yes
aight
Outside it
yeah
And let me know if it works
command = bot.get_command(<command_name>))
command.enabled = False
wait, did I read that wrong
yup
Im sorry
yeah my bad sorry
im trying to make a global disable cmd
sure
this does ^... right?
ah, I just read yours wrong ig
alr, try raising an exception in the on_command event
why an exception?
im trying to iterate over files in a folder to create one choice for each file
try and see
def genchoices():
returnlist = []
for i in os.listdir('Niko_expressions'):
returnlist.append(
create_choice(
name = (i.replace('png', '').replace('_', ' ')),
value = i,
))
return(returnlist)
this is what I have now, but it generates this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 0.options.1.choices.0.name: Could not interpret "[{'value': 'niko_neutral.png', 'name': 'niko neutral.'}, {'value': 'niko_eyebrow.png', 'name': 'niko eyebrow.'}, {'value': 'niko_mouthclosed.png', 'name': 'niko mouthclosed.'}, {'value': 'niko_crying.png', 'name': 'niko crying.'}]" as string.
where should i add an exception i dont really understand why i should add an exception
this is my code again:
@commands.Cog.listener()
async def on_command(self, ctx):
results = collection_cmd.find_one({"guild_id": ctx.guild.id})
if results is None:
pass
elif results is not None and results["disabled"] is not None:
for x in results["disabled"]:
print(x)
print(ctx.command)
if str(x) == str(ctx.command):
break
I'm not sure, but if on_command raises an error, your command won't run, so that way, you might be able to disable certain commands
why should it raise an error
btw mind helping with the above? sorry if you're spread thin
I'm not sure, but your name might need a string, but you're giving it a list? 🤔
yeah, might be because the function was in brackets
this might disable the next command running
getting rate limited from testing, ill give results once im back on
no it shouldnt
that isnt my problem tho
https://stackoverflow.com/a/63502198 this is one option, but I'm not sure if you're even able to prevent a command from running via the on_command event
I found a perfect solution my guy
you'll love it for sure
yeah? tell me
You'll want a global check
this gets checked before every command is invoked and can make it prevent it from running in servers or even specific users!
ohh thanks
you could even handle the CheckFailure that will raise in a global error handler which notifies the author that the command has been disabled 😉
yeah
how would i pass the command?
@client.check
async def dis_cmd(ctx):
results = collection_cmd.find_one({"guild_id": ctx.guild.id})
if results is None:
pass
elif results is not None and results["disabled"] is not None:
for x in results["disabled"]:
print(x)
print(ctx.command)
if str(x) == str(ctx.command):
break
so i currently have this but my commands wont respond my other
how can i pass the commands that arent disabled
you're thinking about this the wrong way
have you seen the link?
it's like 2 lines, the whole check
you could do so too
Hi, I'd like to ask if this code is wrongly used in anyway possible to get a @user_mention?
What am I trying to do?
Mention users without coming up as
invalidon mobile
yeah i did
it can be as easy as
is_disabled = collection......
return is_disabled```
that's literally all you need
then I'd fix your DB structure tbh
what do you mean?
when getting a guild ID, you're getting a list?
a simple SQL query I have in mind is just
SELECT IS_DISABLED FROM GUILDCONFIG WHERE GUILD_ID = ? AND COMMAND_NAME = ?), (guild.id, ctx.command.name,))```
which would simply return the exact value you need
any reason why?
because i find its better and easier
so you've never used with relational databases, right?
i know sql
anyways, you should just get the is_disabled of a specific command in a guild returned in a good query
hi, i would like assistance fixing this on mobile, is this just a bot error?
on desktop the bot shows mentions but on mobile the bot shows @invalid user
huh
your mobile client probably didnt cache the user
it happens on mobile sometimes when someone mentions many users the client hasnt cached yet
It still doesn't work after restarts, do I have to clear cache?
no not at all
Can someone help me on #help-avocado? Please
your client does it by itself
It's discord.py related
But it works for other bots tho
But... other bots although I'm on mobile, it shows userid
I mean user mention
im so confused on your problem. it shows invalid user right but in your desktop client you can see the mention formatted correctly if so then yes your mobile client hasnt cached the user yet
My bot is only showing...
Other bots -- user mention works without any problems, while my bot is showing invalid user. But on desktop, it shows the user.
does this only happens for you?
It happens to everyone else.
then i am correct.
huh
Anyone on mobile, get @invalid user
mention that user yourself
Wym?
why ignore me?
its probably what okimii says
No no, mobile error?
its a common problem in mobile ive seen it myself
That's what I'm confused.
its not mobile its the mobile discord client aka your discord app
Cause every single bot works but my own bot so I'm trying to find the error.
its not your bot!
Wym by didnt cache the user?
Most modern apps use some sort of cache. Discord probably didn't cache that user which is why it shows up that way
since your client hasnt seen it or encountered the user it doesnt cache anything
now their gonna say im right because a helper approved it🙄
Usually though it just shows up as <@432643355634171905>
But... I see the user 24/7 
shows as invalid user in this case
Don't know what's up with that, discord is funky
mobile client lol
mobile ¯_(ツ)_/¯
That's what I don't get 
Not sure, app's weird like I mentioned
its discord what do you expect
I don't get how it's related to app lol
👁️👁️
How else would it vary from desktop to mobile?
desktop client != mobile client
It's not like you can get show something differently if the person viewing your bot is on mobile or not
Yeah you right
Mobile phones tend to handle apps in the background differently
But it’s not always 100% loaded
Lazy loading? sort of at least?
You should just restart your discord app and it’ll render
I'm guessing that's probably the first thing they tried
This is a negligible issue though, you can pretty much ignore it
Well you don't have much choice but to ignore it
I did that.. didn't worked.
It's not only me that can't see it.
Other server members on mobile can't see it.
Well, that's probably on discord's end then
Why wouldn’t they? It’s just an issue on your side
Eventually it’ll fix the cache issue, restarting usually works but sometimes you’ll just have to wait
Perhaps just a coincidence that a bunch of you all are getting the same caching issue
That or discord is goofed and it'll fix itself given due time
The whole server on mobile can't see user mentioned but can see discord 
I'll try restarting
Restarted and its still invalid 
Well, probably a discord issue then. just give it a bit
You sure it can't be a code error?
Yes, because then it'd show the same on both desktop and mobile
If you wanna mention users in your own way, how would you script it?
Does your bot mentions work? Do you do <@{user.id}> to mention?
yes mentions are <@id>
Is it because I put {} brackets it becomes invalid?
Hey
no, as said its your mobile client nothing else.
I cri
How can i make universal error command saying you dont have this perm to use this Etc Not Separate for all one for all
@slate swan ty for explaining
!d discord.discord.ext.commands.on_command_error
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised
inside a command either through user input error, check
failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
youre welcome
I want that it says the perm that is missing @slate swan
just check the class of the error argument
with isintance
does anyone know any free bot hosts?
I was using replit but I can't use always on since I don't have hacker plan
replit is not a host
but many reputable cloud service providers have some sort of free tier
Railway, heroku, CDH and maybe some more all have free plans but I don't recommend you use these since there's a chance your bot will get rate limited easily, also this question is more suited for #965291480992321536
They require a DC/CC no?
Yes, but it's still free in the sense that they don't charge you anything
And most reputable providers will ask you for a CC even if they won't charge you
thanks, also didn't know about that thread
being ratelimited hasn't been too big a problem since I can switch ips whenever it's close / ratelimited
can you do the same with those?
A large amount of bot makers (teenagers) don't have CCs or DCs lol
Unfortunately
But your options are very limited then and you'll have to put up with sub par service
luckily this is an incredibly small bot
so i have a few emotes
called :bar_<size>_<amt>: for progress bars
but i cant get it to actually send them
first attempt it just sent this :bar_left_100::bar_mid_100::bar_right_25:
Not sure
wait hang on
nvm i got it
but it'd be cool if i could just use :name:
instead of <:name:id>
for discord.ui buttons how do i make it so that if a button is pressed the message is edited with the thing i want
!d discord.Interaction.edit_original_message You can use this method ```py
await interaction.edit_original_message(content='Someone clicked my button')
await edit_original_message(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
thx
@keen mural My bad, you're supposed to use Interaction.edit_message
ok 😄 was getting errors
'Interaction' object has no attribute 'edit_message'
Which library are you using?
some github one
Show the error
Ignoring exception in view <Game timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Left' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Desktop\Discord Bot\main.py", line 709, in Left
await interaction.edit_message(embed=embedVar)
AttributeError: 'Interaction' object has no attribute 'edit_message'```
edit_original_message edits the message u sent with inter.send
Mhm
interaction.response.edit_message(...)
this worked thx
although it sent 2 messages
You have two instances of your bot running, cancel the other process/instance or reset your bots token and use the new one to fix it
Does anyone know where I can see a good example of a cog listener with multiple on_message events? I know how to get the cogs working, load them, etc. Im just having trouble determining best practice on how to organize them and conditionally execute in the main file. Like I get that I can put conditions into the cog's event, but Im just having trouble conceptualizing the best way to put it all together so that I can adapt a bot I've already built to a cog-based setup.
thx for the help, also how would i make buttons on different levels this way?
Do you mean rows?
Oh, specify the row kwarg in the button decorator ```py
@button(..., row=0) # 0 = the default row/first row, 1 = the second row and so on
thx again
hi sift 👋
👌
Hello sparky 
and i would disable the button the same way?
you gotta use the commands.Cog.listener() decorator to use events inside a cog it can either be like py @commands.Cog.listener() async def on_message(self, msg): ... or for multiple same events ```py
@commands.Cog.listener("on_message")
async def listener1(self, msg):
...
@commands.Cog.listener("on_message")
async def listener2(self, msg):
...
sup
disabled=True
hi sarth
Yes.. or button.disabled = True if you wanna disable it on press
method name change better than that string
Sup

:D
doing online class :<
string helps you to have multiple same events in a single class/file
hi, sup
Hey sparky
hey 👋
I am not here much nowadays 🥺
Rust?
Yeah I am coding rust
hey skev
Rip 😢
;-;
And it does love giving me errors
man of culture
cool

lol
I like what I name my workspaces as well
They were good
Ok


