#discord-bots
1 messages · Page 368 of 1
How can i start to learn discord bots with python plz?
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
https://automatetheboringstuff.com/ (for complete beginners to programming)
http://greenteapress.com/wp/think-python-2e/ (another decent book)
See also:
http://www.codeabbey.com/ (exercises for beginners)
https://realpython.com/ (good articles on specific topics)
https://learnxinyminutes.com/docs/python3/ (cheatsheet)
first learn python with that ^
then use the official examples at https://github.com/Rapptz/discord.py/blob/master/examples
skibidi dop dop yes yes dabaru dabaru
thx so much
@pale zenith what is the error? py embed = discord.Embed(color=color_lace) embed.set_image(url=pfp_url) embed.set_footer(text=f"{self.bot.user.name} | autopfp", icon_url=self.bot.user.avatar.url) embed.timestamp=discord.utils.now()
@pale zenith what is the error sir 👌
@pale zenith excuse me, what is the error
@pale zenith heya, what is the error
everyone asks what is the error, nobody asks how is the error 😔
@pale zenith you day are good?
anyway
send the error lol, idk what you expect me to say from that
actually I do. it is discord.utils.utcnow() not .now()
and both bot.user and user.avatar are optional

Error: list index out of range```
@pale zenith my love language
@pale zenith i love u
love you too
help?
Traceback (most recent call last):
File "C:\Users\ethan\Downloads\Downloads\Tools\My Tools\Whitey Selfbot\Whitey Selfbot\Whitey Selfbot\main.py", line 1656, in <module>
leakedsb.run(token, bot=False)
TypeError: Client.run() got an unexpected keyword argument 'bot'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000249B4CE5250>
C:\Users\ethan\Downloads\Downloads\Tools\My Tools\Whitey Selfbot\Whitey Selfbot\Whitey Selfbot>
my friend needs help and idk where to ask
Anyone interested in making a anime bot
bot=False ?
Interesting
All self bot related features have been deprecated since dpy 1.7.3 and removed later on
And I don't think helping with self bots is allowed
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@bot.tree.command(name="start", description="Start a player")
async def start(interaction: discord.Interaction, member: discord.Member):
embed = discord.Embed(description=f'{member.mention} has been made a starter.', timestamp=datetime.now(), color=discord.Color.from_rgb(0,255,0))
guild = interaction.guild
role = discord.utils.get(guild.roles, id=1241892185457033236)
await member.add_roles(role)
await interaction.response.send_message(embed=embed)```
idk why im getting error but i am
your bot doesn't have perms to add roles
Or your bot doesn't have permissions to add role to anyone
?jsk py
ow = discord.PermissionOverwrite()
ow.send_messages=False
await channel.set_permissions(guild.default_role, overwrite=ow)```
discord.py==2.3.2
According to me this code is supposed to set only send_messages to False, but it also resets other permissions along with setting send_messages to False. How do I prevent this?
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
selfbot 😂
Instead of making a new permission overwrite instance, get the existing permissions of the channel
ow = channel.overwrites[role to edit]
ok
@bot.tree.command(name="raid", description="Find nations to raid")
async def raid(interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
db = DatabaseUser()
user_id = interaction.user.id
nation_id = await db.get_user_nation_id(user_id)
if nation_id is None:
await interaction.followup.send(
"Error message",
ephemeral=True
)
return
query = kit.query("nations", {"id": int(nation_id)}, "score")
result = query.get()
if result and "nations" in result:
nation = result["nations"][0]
score = nation["score"]
else:
await interaction.followup.send(
"Unable to retrieve your nation score.",
ephemeral=True
)
return
min_score = int(score) * 0.75
max_score = int(score) * 1.75
query = kit.query("nations", {
"min_score": min_score,
"max_score": max_score,
"vmode": False,
"color": ["blue", "yellow", "black", "orange", "red", "green", "white", "purple", "brown", "gray", "lime", "aqua", "pink", "maroon"],
"first": 1000
}, """
id, nation_name, score, wars{def_id, def_resistance, att_money_looted}, alliance{name}, alliance_position_info{name}, num_cities, vacation_mode_turns, soldiers, tanks, aircraft, ships, color, leader_name, last_active
""")
result = query.get()
if result and "nations" in result:
nations = result["nations"]
# Filter and sort nations based on ended wars and money looted
filtered_nations = []
for nation in nations:
total_money_looted = sum(
war["att_money_looted"]
for war in nation["wars"]
if war["def_resistance"] == 0
wars
)
if total_money_looted > 0:
filtered_nations.append((nation, total_money_looted))
filtered_nations.sort(key=lambda x: x[1], reverse=True)
top_nations = filtered_nations[:10]
embed = discord.Embed(title="Top Nations to Raid", color=discord.Color.blue())
for nation, money_looted in top_nations:
embed.add_field(
name=nation["nation_name"],
value=(
f"**Score:** {nation['score']}\n"
f"**Money Looted:** ${money_looted}\n"
f"**Alliance:** {nation['alliance']['name'] if nation['alliance'] else 'None'}\n"
f"**Leader:** {nation['leader_name']}\n"
f"**Cities:** {nation['num_cities']}\n"
f"**Last Active:** {nation['last_active']}\n"
),
inline=False
)```
await interaction.followup.send(embed=embed, ephemeral=True)
else:
await interaction.followup.send(
"Unable to retrieve nations for raiding.",
ephemeral=True
)```
Huh, 3 parts, btw I'm getting an error: Argument of type 'Result' is not iterable
In console
How'd I get the channel ID a command was invoked in?
what is
await Bot.process_commands(message)
?
for text commands
Context.channel.id
for slash commands
Interaction.channel.id```
where Context and Interaction are to be replaced with their respective instances from the commands
it matches all the text/message commands that are in your code and runs them if applicable
what does query.get() return
It has to return nations from query
You want some other command codes for seeing example?
Can I see the output?
Traceback?
I didn't got any output in discord but I was expecting to get
no I want to see what query.get returns
That code didn't gave any output
But I have other commands wait
query = kit.query(
"nations", {"id": int(nation_id)},
"""nation_name, leader_name, color, num_cities, vacation_mode_turns, soldiers, tanks, aircraft, ships, alliance { name }, alliance_position_info { name }, date"""
)
result = query.get()
if result and result.nations:
nation = result.nations[0]
embed = discord.Embed(
title="Registration Info",
description=f"Registered with nation ID: {nation_id}",
color=discord.Color.orange()
)
embed.add_field(name="🇺🇳Nation Name",
value=nation.nation_name,
inline=True)
embed.add_field(name="👑Leader Name",
value=nation.leader_name,
inline=True)
embed.add_field(name="⏳Created",
value=f"`{creation_message}`",
inline=False)
embed.add_field(name="🎨Color",
value=nation.color.capitalize(),
inline=True)
```
embed.add_field(name="🏙️Cities",
value=nation.num_cities,
inline=True)
embed.add_field(
name="📴Vacation Mode",
value=f"{nation.vacation_mode_turns} Turns",
inline=True)
if nation.alliance:
embed.add_field(name="🕍Alliance",
value=nation.alliance.name,
inline=True)
if nation.alliance_position_info:
embed.add_field(
name="💼Alliance Position",
value=nation.alliance_position_info.name,
inline=True)
embed.add_field(name="💂Soldiers",
value=nation.soldiers,
inline=True)
embed.add_field(name="🚜Tanks",
value=nation.tanks,
inline=True)
embed.add_field(name="🛩️Aircraft",
value=nation.aircraft,
inline=True)
embed.add_field(name="🚢Ships",
value=nation.ships,
inline=True)```
whats kit here?
looks ind of like graphql query
Ok
btw print out result here to see what ur getting
if result and "nations" in result:
nations = result["nations"]```
Has errors bro
Operator "in" not supported for types "Literal['nations']" and "Result"
Ok
'Await' outside function
??
It worked when I remove await and async
import pnwkit
# Initialize pnwkit with your API key
kit = pnwkit.QueryKit("key")
query = kit.query("nations", {
"min_score": 500,
"max_score": 1000,
"vmode": False,
"color": ["blue", "yellow", "black", "orange", "red", "green", "white", "purple", "brown", "gray", "lime", "aqua", "pink", "maroon"],
"first": 300
}, """
id, nation_name, score, wars{def_id, def_resistance, att_money_looted}, alliance{name}, alliance_position_info{name}, num_cities, vacation_mode_turns, soldiers, tanks, aircraft, ships, color, leader_name, last_active
""")
result = query.get()
print(result)```
Anyone know how lazy servers work?
Like the ones you don't get msgs by just connecting you gotta send a packet
@shrewd apex this gave me results in console
and the result is?
pnwkit/new.py line 966
class Result:```
can u do print(result.nations)
Ok
import pnwkit
# Initialize pnwkit with your API key
kit = pnwkit.QueryKit("key")
query = kit.query("nations", {
"min_score": 500,
"max_score": 1000,
"vmode": False,
"color": ["blue", "yellow", "black", "orange", "red", "green", "white", "purple", "brown", "gray", "lime", "aqua", "pink", "maroon"],
"first": 300
}, """
id, nation_name, score, wars{def_id, def_resistance, att_money_looted}, alliance{name}, alliance_position_info{name}, num_cities, vacation_mode_turns, soldiers, tanks, aircraft, ships, color, leader_name, last_active
""")
result = query.get()
print(result)
nation_name = result.nations[0]["nation_name"]
print(nation_name)```
yeah so the query works
if result and "nations" in result:
nations = result["nations"]
this however is wrong because result is not a dictiorary of such data it is a class
what u want to do is just
nations = result.nations
I have to remove that?
From the code?
it does pretend to be one tho
https://github.com/mrvillage/pnwkit-py/blob/master/pnwkit/data.py#L102-L106
pnwkit/data.py lines 102 to 106
def __getitem__(self, name: str) -> Any:
try:
return self.__getattribute__(name)
except AttributeError as e:
raise KeyError(name) from e```
oh wait nevermind, the other data classes inherit that method but not result itself
Do I have to remove that from the code then?
yep
Ok
lol u should see their documentation on the result class https://docs.pnwkit-py.mrvillage.dev/en/latest/api.html#result
0|bot | Traceback (most recent call last):
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/root/core/errors.py", line 130, in on_command_error
0|bot | raise error
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 235, in wrapped
0|bot | ret = await coro(*args, **kwargs)
0|bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
0|bot | File "/root/cogs/moderation.py", line 665, in nick
0|bot | await member.edit(nick=nick)
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/member.py", line 914, in edit
0|bot | return Member(data=data, guild=self.guild, state=self._state)
0|bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/member.py", line 348, in __init__
0|bot | self._user: User = state.store_user(data['user'])
0|bot | ~~~~^^^^^^^^
0|bot | TypeError: string indices must be integers, not 'str'```
```py
async def nick(self, ctx: Context, member: discord.Member, nick: str = None):
await member.edit(nick=nick)```
My nick command used to work fine but I don't know why I am getting this error today.
@pale zenith
they took conciseness to another level
ur data here is a string
shouldn't be
and ur basically trying to do "some_string"['user']
but member is discord.Member object
feels like a discord.py bug
ya, that documentation has no examples/quickstart and the library uses some odd module names, but at least from a glance the source code looks fairly competent
yep
u sure the member is someone the bot has access to aka is in the server
this is a bit weird
yes ofc
oh, it works
but gives error
what discord.py version are you using? it kind of looks like the API response was malformed
hmm, looks like 2.3.2 as usual...
is the error reproducible?
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/member.py#L912-L914
the TypeError would suggest await http.edit_member() received a non-json response, but why would the API return that without some abnormal status code?
discord/member.py lines 912 to 914
if payload:
data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
return Member(data=data, guild=self.guild, state=self._state)```
random guess, can you try to do the raw API request and print out what it returns? py data = await ctx.bot.http.edit_member(ctx.guild.id, member.id, nick=nick or "") print(data)
ok
doesn't print anything
not even an empty line?
nah
i would expect at least something to be printed, even if it was an error
oh, at least that means the code did run
presumably it returned an empty string... that doesnt seem right
lemme try to reproduce this lol
i tested a minute ago and couldnt repro it
hmm
can you yield (type(data), repr(data)) just to be certain that its an empty string?
afterwards you can include the result of that command in your bug report
do you think it could be an intents thing? your intents are quite minimal, but the most important one is guilds which you have, plus the api docs dont describe a situation where editing a member would return an empty body...
not intent issue as because the same code used to work a few days ago
i got this error today only
nope couldnt reproduce
💀
.
actually
you should mention that in your issue too...
ok
cc @spice warren 
that is probably your issue btw. whatever the fuck that library is doing is fucking with the api. consider not using it?
mfw raising it here instead of answering on the github issue they made
they pinged me here directly
check
this person is already being helped, feel free to disregard
they are also banned from discord.py for being rude and offensive to helpers, do with that information what you will
noted
wait, so this twilight-http-proxy is a discord API mock?
no
Yeah.
handles request in a better way which doesn't cause CF Bans
http-proxy looks to be the proxy itslef, while twilight-http-proxy seems to be a handler for twighlight-http which accounts for the fucked up api responses that the proxy returns
This is not how you avoid CF bans at all, lol
Discord.py already does what it can to prevent you getting banned, but terrible user code often wins
You were told this numerous times and the arguments that ensued are what led to your ban
Oh I remember this peson now
Yep
antiraid bot innit
Yep

antinuke*
Aka reverting something that someone did with permissions that they shouldn't have
Hi guys. Help pls. How to create a ephemeral message?
ephemeral = True
Where?
In interaction.response.send_message
Or in ctx.send if its a hybrid command
Hi guys!
How do i install discord.py in replit? Using python
pip install discord.py in the shell tab
Ooohhh
while sending the message
Okay thank you thank god
god 💀
example:
await interaction.response.send_message("Hello", ephemeral=True)
You can only send an ephemeral on response to an interaction
So when invoking that command via the slash menu
Setting the prefix to "/" doesn't do anything special
Hello, does anyone have good tutorial about slash commands in Cogs? I wrote simple bot with one cog and run into error which i cant fix. I tried every possible solution on internet but nothing worked. I created post on python-help but noone answered. Can someone help me with this?
OK i found my problem, i pass server id as string not int 🤣
You also should not be syncing in on_ready (or probably doing anything in it)
yeah, i've already move those parts to setup hook
not better 💀
btw have you turned on type checking? pylance might have been able to detect that mismatched type before you ran the bot
why not? many sources i found on the internet syncing slash command in setpu hook or on_ready function and it works.
"works" and "is optimal" are two different things
hmm in this case I guess not.
well its recommended to sync usually only when u change ur command signatures, or define new or remove commands which u might not always do everytime
for self taught like me "works" is good enough
you should turn it on then, its quite useful given that dpy has plenty of typehints to analyze
What does being self-taught have to do with it, aren't we all self-taught since you can't really take a university course on discord.py? Anyway, wouldn't you strive for the best, and not settle with something that works? It's of course up to you, but I'm just saying that there's a better way to do things.
dpy uni course 💀
first class debate on different libraries dpy vs disnake vs pycord/nextcord (honorable mention hikari)
only really different one being hikari
You are right but improvement comes along with time and experience. Now I just want to make a bot, play with it and have fun. If you have some good learning material I'd be happy to take a look at them.
could anyone help me with slash commands?
i am trying to make a command which returns the pfp of the user
That's fine
@client.tree.command(name="image", description="Displays the avatar of a user.")
async def avatar(ctx, member: discord.Member = None):
if member == None:
member = ctx.author
embed = discord.Embed(title = member).set_image(url = member.avatar.url)
await ctx.send(embed = embed)
slash commands dont have context
so how would i send the image?
The user or member that sent the interaction.
thanks
Discord.py allows for several ways to create/define application commands within it’s codebases. In this page we’ll go through several of these.
so how would i send the message
instead of ctx
yea
await interaction.response.send_message(...)
cool
You can code discord bots in any language that supports web requests
the best of 'em all is
nextcord
(doesn't support files in some places yet)
i know what you want to hear
say it then 🔫
na
say it
Say it right now
hey! i want to make a function of my bot to just stop if its on a thread this is for a very specific reason that will take me a while to explain, lets say i just want to say:
return```
Can check the type of message.channel
do you have any reference for that? :0
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
- using isinstance to see if it's type is Thread
@pale zenith great dear sir, could you help me? please
Does anyone have a bot like restorcord?
that's so weird... it just doesn't send the image for me. :/
async def create_table_roles(self):
conn = await self.get_connection()
async with conn.cursor() as cursor:
await cursor.execute('''CREATE TABLE IF NOT EXISTS roles (
guild_id INTEGER PRIMARY KEY,
members TEXT,
leader TEXT
)''')
await conn.commit()
async def add_guild_members(self, guild_id, members):
conn = await self.get_connection()
async with conn.cursor() as cursor:
await cursor.execute("INSERT OR REPLACE INTO roles (guild_id, members) VALUES (?, ?)", (guild_id, members))
await conn.commit()
async def add_guild_leader(self, guild_id, leader):
conn = await self.get_connection()
async with conn.cursor() as cursor:
await cursor.execute("INSERT OR REPLACE INTO roles (guild_id, leader) VALUES (?, ?)", (guild_id, leader))
await conn.commit()
async def get_guild_roles(self, guild_id):
conn = await self.get_connection()
async with conn.cursor() as cursor:
await cursor.execute("SELECT members, leader FROM roles WHERE guild_id=?", (guild_id,))
result = await cursor.fetchone()
return {"members": result[0], "leader": result[1]} if result else None```
Command 1
@bot.tree.command(name="roles", description="Set roles with Dominion")
@app_commands.describe(members="Role for your alliance members", leader="Role for your alliance leader")
async def roles(interaction: discord.Interaction, members: discord.Role, leader: discord.Role):
if not interaction.user.guild_permissions.administrator:
return await interaction.response.send_message("You do not have permission to use this command.", ephemeral=True)
guild_id = interaction.guild.id
# Add roles in the database as text
await db.add_guild_members(guild_id, str(members.id))
await db.add_guild_leader(guild_id, str(leader.id))
await interaction.response.send_message("Roles added successfully!", ephemeral=True)```
Command 2
@bot.command(name="check")
async def check(ctx):
guild_id = ctx.guild.id
roles = await db.get_guild_roles(guild_id)
if roles:
members_role_id = roles.get("members")
leader_role_id = roles.get("leader")
await ctx.send(f"Members Role ID: {members_role_id}, Leader Role ID: {leader_role_id}")
else:
await ctx.send("No roles found for this guild.")
It says roles added successfully but when I retrieve roles then it says members as none
how to make a discord selfbot to auto accept friend requests
You don't get selfbot help anywhere, they're against ToS.
Why the check @commands.bot_has_permissions(move_members=True) returns False even if the bot has admin permission but not with @commands.bot_has_guild_permissions(move_members=True)
@spice warren
I refuse to help racist and rude people
Channel (and role?) vs Guild perms
but bot has admin permission
Also text vs voice channel
move_members will be False in a text channel iirc
Idk how exactly perms work
oh
Your bot should not have admin
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
what? why not
can i somehow make private threads??
sure, TextChannel.create_thread() creates private threads by default
huhh?? i thought it creates a public thread
why should I remove admin permission?
type (Optional[ChannelType]) – The type of thread to create. If a message is passed then this parameter is ignored, as a thread created with a message is always a public thread. By default this creates a private thread if this is None.
because it literally has every permission
you don't need it all unless you use it all or it's in a test server
ohh, thank you
You don't have to
is there a minimum archive minute thing
auto_archive_duration=15
i have it set to 15
i don't need to give it admin perms??
no??
That's what I'm saying xd
why will i remove admin permission?
safety
What they are trying to say is that the bot should only have the permissions it will use, the others are not necessary
bro
according to the same docs, only 60, 1440, 4320, or 10080 are allowed
In my opinion, that's a thing of preference
my question is, the bot has admin permission which means the bot has all the permissions
but still it says that the bot doesn't have the permissions
and check is failed
Did you invited the bot with admin permissions?
yes.
also enabled all the intents?
not presence intent
can I see the error message, that's weird
no error, it says move_members permission is set to False
?jsk py channel.permissions_for(ctx.me).move_members```
got it, move_members is false for text channels and not for voice channels as said above by soheab.
and thats in minutes???
im digging through the discord.py src, f that
that aint just a dpy thing, its a discord API restriction
https://discord.com/developers/docs/resources/channel#start-thread-without-message
you can tell cause the error you got was 400 Bad Request, which only comes from sending the discord API something invalid
oh 😔
how do i check if someone has reacted to a message the that bot has add reactions to, in a @app_commands.command
I am making a quiz game, and the bot reacts with 4 emojis, and i want it to detect if you choose the correct one
There is no reason, literally, to give a bot more permissions than it needs to do its stated purpose besides laziness
If you are optimizing on saving 5 whole ass minutes of scrutinizing what your bot needs to do, your priorities are hilariously wrong
@hushed galleon sorry for disturbing but how can i give my bot like 4 shards?
hi leonardo
uhh, AutoShardedBot(shard_count=4) i presume? i dont touch sharding all that much
Yo
side note: adding more shards changes nothing if it's all in a single process
ive wondered that too, dpy doesnt mention using any form of IPC or whatnot with sharding
wdym by this??
like 4 shards will act like 1 shard?
or rather the doc explicitly says the opposite, "not having to deal with IPC or other complicated infrastructure"
what is the point of AutoShardedClient then? for bots in 2500+ guilds that arent yet performance constrained?
More like you don't gain any performance increase by using a single auto sharded client. It's still a single event loop and a single process
Pretty much
Friend of mine had a bot in 100k guilds on a single process, then it was too much and had to do actual, proper clustering and shit, and now he's rewriting the entire bot
huh, dpy's shard support must be simpler than i imagined
definitely sounds like it'd be a tough journey restructuring a single process bot for that scale
well, i guess it depends on how much shared memory / cached stuff you were relying on
Each shard gets an asyncio task that wraps a worker coro, and there's a main loop which handles the things that the worker _queue_puts.
The actual websocket class is the same as a normal client's, except there are multiple websocket connections. One for each shard. So the logic is the same for dispatching events etc, except it receives events from multiple ws
looking at that disconnect handling reminded me of the weirdness i did when i tried writing my gateway wrapper, specifically having to unwrap the first exception out of a group to handle it
https://github.com/thegamecracks/discord-ws/blob/main/src/discord_ws/client/client.py#L239-L250
src/discord_ws/client/client.py lines 239 to 250
try:
async with self._connect(gateway_url) as ws:
await self._handle_connection(session_id=session_id)
except* ConnectionClosed as eg:
# Multiple errors should still be from the same connection,
# so we're only interested in handling the first occurrence
e = _unwrap_first_exception(eg)
assert e is not None
reconnect = self._handle_connection_closed(e) and reconnect
except* (GatewayInterrupt, HeartbeatLostError):
if not reconnect:
raise```
and that was only for one connection, im still not sure how i'd rewrite it to avoid exception groups here
class IDK(discord.ui.View):
def __init__(self,
bot
):
self.bot = bot
...
self._panel_pending = False
self.pending_panel_message: discord.Message = None
super().__init__(...)
@discord.ui.select(
...
)
async def callback(self, intr: intr, select: Select):
if self._panel_pending is True:
await self.pending_panel_message.delete()
self.pending_panel_message.components[0].stop()
view = Panel(...)
self.pending_panel_message = await intr.response.send_message(
...
view=view
)
print(self.pending_panel_message)
self._panel_pending = True
await view.wait()
self._panel_pending = False```
how is self.pending_panel_message None?
u set it to None?
sup fellas 
hell
did my python3.11 interpreter die
!d discord.Interaction.send_message
huh isnt this script from the official dpy example?
seems familiar
?
nvm point is send_message returns None
u need to use original_response()
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None, poll=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
coro
i see
first time I've ever seen except*
that is cool though
iirc it should be @app_commands.checks.cooldown
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown) is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
so at least 2 args, rate/per
-- Code goes up there
if contentEnabled and embedEnabled and buttonEnabled is True:
try:
await member.send(content = contentText.format(member = member, guild = guild), embed = embed, view = view)
console.success(f"Sent message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX})")
except Exception as e:
console.error(f"Failed to send message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX}) {e}")
elif embedEnabled and buttonEnabled is True:
try:
await member.send(embed = embed, view = view)
console.success(f"Sent message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX})")
except Exception as e:
console.error(f"Failed to send message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX}) {e}")
elif contentEnabled and buttonEnabled is True:
try:
await member.send(content = contentText.format(member = member, guild = guild), view = view)
console.success(f"Sent message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX})")
except Exception as e:
console.error(f"Failed to send message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX}) {e}")
elif contentEnabled and embedEnabled is True:
try:
await member.send(content = contentText.format(member = member, guild = guild), embed = embed)
console.success(f"Sent message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX})")
except Exception as e:
console.error(f"Failed to send message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX}) {e}")
elif contentEnabled is True:
try:
await member.send(content = contentText.format(member = member, guild = guild))
console.success(f"Sent message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX})")
except Exception as e:
console.error(f"Failed to send message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX}) {e}")
elif embedEnabled is True:
try:
await member.send(embed = embed)
console.success(f"Sent message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX})")
except Exception as e:
console.error(f"Failed to send message to: {Fore.MAGENTA}{member}{Fore.LIGHTBLACK_EX} ({Fore.MAGENTA}{member.id}{Fore.LIGHTBLACK_EX}) {e}")```
How could I make the bot leave the guild it's messaging users on once it's finished
I tried using guild.leave but it didn't seem to work
thanks, how do i make an error handler for it aswell
sounds like its being used for malicious purpose ngl
? Used for a giveaway bot which reminds people to click the "claim button" once the giveaway is done
i also think that
^
^
then why would u wanna guild.leave
for a server event
yeah it doesnt 💀
:fall:
no errors raised?
nope
you aren't consuming/handling the errors?
dont think so
??
thegamecracks has been typing for a while now lol
yas im thinking
okay
ah i remember now, the receive loop and heartbeat run in different tasks so my TaskGroup wraps it in an exception group in case both fail at the same time... im still not sure how i would write a handler that would check every exception instead of ignoring the rest... i guess .subgroup(predicate) would be involved?
have you written error handlers for slash commands before?
perchance
@bot.tree.error
async def on_error(interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
if isinstance(error, app_commands.CheckFailure):
try:
await interaction.response.send_message(f"No permission!")
except discord.InteractionResponded:
await interaction.followup.send(f"No permission!")
else:
raise error```
did this a while ago idk if it'll still work
the cooldown doc has an example that includes a local error handler for the command, but putting it in your global handler would be a good idea: py @bot.tree.error async def on_tree_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(f"You're on cooldown for {error.retry_after} seconds!", ephemeral=True) else: raise error
!d discord.app_commands.CommandOnCooldown
exception discord.app_commands.CommandOnCooldown(cooldown, retry_after)```
An exception raised when the command being invoked is on cooldown.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0.
found it lmao
right, attributes dont show in the embed... well anyway the exception has a .cooldown attribute if you want to show the rate/per limit too
how do you like untimeout someone 💀
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
If None is passed then the timeout is removed
How can I implement set values for an argument, using interaction
Heyyy, anyone want to get reputation on stack overflow
if entry.action == discord.AuditLogAction.channel_delete:
channel = entry.target```
why is channel an Object and not a text/voice channel
0|bot | [2024-05-22 06:57:19] [ERROR ] discord.client: Ignoring exception in on_audit_log_entry_create
0|bot | Traceback (most recent call last):
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/root/Events/", line 401, in antinuke_audit_log_entry
0|bot | new_channel = await channel.clone()
0|bot | ^^^^^^^^^^^^^
0|bot | AttributeError: 'Object' object has no attribute 'clone'```
the API probably does not provide enough data on that endpoint for dpy to construct a TextChannel/VoiceChannel
you can get the id of the channel and getch it
ok
but the channel is deleted so i don't think I can fetch it
if entry.action == discord.AuditLogAction.channel_delete:
channel = entry.target```
well. try to get it
it is None
Can I ues python let the arduino development board recognize the QR code and trigger specific actions based on different QR codes, such as controlling the switch and brightness of the light?
@pale zenith how do I get TextChannel/VoiceChannel object?
do i need to store it in cache in the on_guild_channel_delete event?
Hello guys wassup
If it's deleted how is it meant to be cloned
Pure hope
if i send the command the bot respond me twice, and i cant put await because is a traceback
You shouldn't be doing those things in on_ready. That event fires repeatedly and randomly
so how where i put the cog
setup_hook
What library and version are you using?
mean discord.py?
Subclass Bot and override it
Adding cogs is async as of 2.0
some sample?
Instead of doing async setup in on_ready, or using a task which may lead to events being called before that task runs, you can overwrite Client/Bot.setup_hook.
For example: ```py
subclassing commands.Bot
class MyBot(commands.Bot):
# overriding setup_hook and doing our stuff in it
async def setup_hook(self):
# self is the bot here
print(f"Logged in as: {self.user}")
# can load your extensions here:
# await self.load_extension(...)
using the class:
bot = MyBot(command_prefix=..., intents=..., ...)
notice how we previously used:
bot = # commands.Bot(command_prefix=..., intents=..., ...)
but now our subclass.
Docs: https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.setup_hook
-_- im dumb
What isn't working?
Also, show more code. You most likely have an on_message listener somewhere
If you're adding cogs, we're going to need that code too
mmmm ok
wait
from discord.ext import commands
from variables import TOKEN, ACTIVIDAD,PREFIX
from comandos.general.help import Help
intents = discord.Intents.all() #all / default
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
cogs = [Help]
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name=(ACTIVIDAD), url="https://www.youtube.com/) #Streaming/Idle/Playing
print(f'¡Bot {bot.user.name} conectado!')
for cog in cogs:
bot.add_cog(cog(bot))
bot.run(TOKEN)```
commands/general/help.py
from discord.ext import commands
import discord
class Help(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command()
async def help(self, ctx):
await ctx.send(f'Enviado a {ctx.author.mention}')
def setup(bot):
bot.add_cog(Help(bot))```
cogs= [help, meme, search,...]
Take all of the code out of on_ready and put it in the right place, first
Any of these cogs could be changing behavior
class Ayuda(commands.Cog):
bot.add_cog(Help(bot))```
your class name isnt Help
wait
but the error isnt the name
ik i was just pointing that out
.
hi i need a little bit help.
So i made a bot in python on windows he works perfectly but on my rpi to host it, it doesn't work cuz the font i use for the welcome message
Idk how i can fix it ping me
I use a custom font .ttf
What does "welcome message" mean here
ik but the bot send me twice 😦
.
the image the bot sends when a ppl joins the server
So you're generating an image then? With something like PIL?
ye w PIL
What's the error?
But on my rpi the .ttf font doesn't work
File "/home/ju/Desktop/FEBOT/myenv/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/ju/Desktop/FEBOT/bot.py", line 71, in on_member_join
await send_welcome_message(member, welcome_channel)
File "/home/ju/Desktop/FEBOT/bot.py", line 78, in send_welcome_message
welcome_image_path = await create_welcome_image(member, welcome_message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ju/Desktop/FEBOT/bot.py", line 91, in create_welcome_image
font = ImageFont.truetype(font_path, 20)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ju/Desktop/FEBOT/myenv/lib/python3.11/site-packages/PIL/ImageFont.py", line 807, in truetype
return freetype(font)
^^^^^^^^^^^^^^
File "/home/ju/Desktop/FEBOT/myenv/lib/python3.11/site-packages/PIL/ImageFont.py", line 804, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ju/Desktop/FEBOT/myenv/lib/python3.11/site-packages/PIL/ImageFont.py", line 244, in __init__
self.font = core.getfont(
^^^^^^^^^^^^^
OSError: cannot open resource
Bro i'm dumb asf, linux systems send an error when the syntax isn't good like a capital.
someone can help me ;-;
Again
You have shared one file
u probably need to install the font in ur rpi b4 u can use it
https://github.com/waveshareteam/e-Paper/issues/2 a similar case i found
No i just forgot to call my fonts Vintage with a capital
i can send u the zip on dm
lol
GitHub or mystbin would be ideal
anyone know how to check if someones a thread owner?
!d discord.Thread.owner
property owner```
The member this thread belongs to.
another question
how do i use choices cuz im struggling
in what sense?
hello im creating a discord bot for a slash command blah blah anyways how can i make it ask for an image when using / command?
my friend said something about being able to upload a 25mb image
any hints? 🙂
im using hybrid for slash commands
Add a parameter to your command callback and set the type-hint to discord.Attachment
thanks
it's good to give them the flexibility to either give a url Or an image
wow this is the deadest ive seen the chat
How do I mention a role in a select menu?
Ive tried the following:
discord.SelectOption(label=role.mention)
discord.SelectOption(label=role)
discord.SelectOption(label=role.name)
is that even a discord bots related problem?
No, now that i think of it
thanks gang
😉
I think you can't, but you can use RoleSelect
!d discord.ui.RoleSelect
class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.
Please note that if you use this in a private message with a user, no roles will be displayed to the user.
New in version 2.1.
How can I reach the latest message from each channel in a category on on_ready?
lfg_category_id = 1204554345815875606
last_user_message = {}
class MyClient(commands.Bot):
async def on_ready(self):
for guild in self.guilds:
# Find the category by ID
category = discord.utils.get(guild.categories, id=lfg_category_id)
if category:
for channel in category.text_channels:
# Fetch the latest message for each text channel
async for msg in channel.history(limit=1):
last_user_message[channel.id] = msg
Or is there any better way to do it?
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
Short of it is no, you shouldn't use on_ready for 99.9% of things
print(“hello world”)
syntax error
You are right, I'm going to fetch the messages dynamically by using on_message instead
i need help pls :
bot.py :
import discord
from discord.ext import commands
import commandes
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='+', intents=intents)
@bot.event
async def on_ready():
print(f'Le bot {bot.user.name} est prêt !')
# Charge la cog Commandes
bot.load_extension("commandes")
bot.run('TOKEN')```
import discord
from discord.ext import commands
class Commandes(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def addeleve(self, ctx, classe: str, nom_eleve: str):
"""Ajoute un élève à une classe spécifique."""
# Code pour ajouter l'élève à la base de données et afficher un message de confirmation
await ctx.send(f"{nom_eleve} a été ajouté à la classe {classe} avec succès !")
@commands.command()
async def listeclasses(self, ctx):
"""Affiche la liste des classes."""
# Code pour afficher la liste des classes
await ctx.send("Voici la liste des classes :\n- Classe 1\n- Classe 2\n- Classe 3")
@commands.command()
async def listeeleves(self, ctx, classe: str):
"""Affiche la liste des élèves d'une classe spécifique."""
# Code pour afficher la liste des élèves d'une classe
await ctx.send(f"Voici la liste des élèves de la classe {classe} :\n- Élève 1\n- Élève 2\n- Élève 3")
@commands.command()
async def supprimeleve(self, ctx, nom_eleve: str):
"""Supprime un élève de la base de données."""
# Code pour supprimer l'élève de la base de données
await ctx.send(f"{nom_eleve} a été supprimé de la base de données avec succès !")
@commands.command()
async def menu(self, ctx):
"""Affiche le menu des commandes."""
# Code pour afficher le menu des commandes
embed = discord.Embed(title="Menu des commandes", description="Voici la liste des commandes disponibles :", color=0x00ff00)
embed.add_field(name="+addeleve", value="Ajoute un élève à une classe spécifique", inline=False)
embed.add_field(name="+listeclasses", value="Affiche la liste des classes", inline=False)
embed.add_field(name="+listeeleves <classe>", value="Affiche la liste des élèves d'une classe spécifique", inline=False)
embed.add_field(name="+supprimeleve <nom_eleve>", value="Supprime un élève de la base de données", inline=False)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Commandes(bot))
my error :
discord.ext.commands.errors.CommandNotFound: Command "menu" is not found```
or other commands
What library and version are you using?
For shards do you only need Autoshandebot or do you need to do something else?
well, if there's anything to use on_ready for it'd be that, because on_ready is your chance to deal with any events your bot missed since the last disconnect - my main reason to go with on_message here would be not wanting to make X requests on every channel, even if it means the cache being inconsistent for some time
#discord-bots message if you're not looking for performance benefits and just need your bot to work with a large number of guilds, then sure you can use that
And what could I do to benefit performance?
split your bot into multiple processes and coordinate their sharding so they each handle a subset of the guilds your bot is in
a database, message queue, or some other form of IPC may be necessary to make certain features of your bot work properly under that architecture
running those processes on separate computers might also help if you're starting to exceed the capabilities of a single system, but at that point you might want some orchestration software like kubernetes or whatev (tbh horizontal scaling is beyond my knowledge)
Would you do this in a different way? What do you think of the code? https://paste.pythondiscord.com/N2VA
wouldn't that require some form of a load balancer to coordinate between shards
ergh, hard to avoid a history() call in this use case for reliability, but i would suggest fetching at least the last 100 messages (1 API call) exactly once after on_ready, because only storing 1 message might make you miss out on that user's last message if someone else posted something
isn't discord already load balancing based on shard ID? or do you mean something different?
does it haven't used sharding much at all would discord send requests to particular shards to which a guild is assigned which that particular bot shard would receive directly?
what happens if a particular shard is down does it get forwarded to some other shard?
https://discord.com/developers/docs/topics/gateway#sharding
DM events go to shard ID 0 while guild events go to the shard ID calculated by (guild_id >> 22) % num_shards
presumably if a shard goes down, you don't get to receive events from that subset of guilds
i see ty 😄
this might be a bit interesting to test and play with I'll try it out this weekend
whats some common refactoring do u reckon sharded bots would require
The goal is to prevent a member from sending multiple messages in a row without another member posting in between.
oh, then limit=1 would be fine
We just need to compare it with the latest message
a different thing, if you're only handling on_message then you dont need to check that their message IDs are different
You mean that message.channel.id and message.author.id should be enough?
That is actually true
also wouldnt that mean mapping author ID to message ID is unnecessary?
just mapping channel ID to author ID would be enough to know if a new message is consecutive
well i guess message ID too for deletion
Oh yeah
oh right, still need message to delete it
{channel ID: message obj} then, which is also kinda close to the built-in channel.last_message
though the latter is a bit less reliable since it uses the bot's message cache, capped to 1k messages by default
@commands.hybrid_command()
@commands.guild_only()
@app_commands.describe(emoji="Please give a discord Emoji.")
async def clone(
self, ctx: commands.Context, emoji: discord.PartialEmoji, name=None
):
"""
Clone any emoji you would like from any server even if the bot isn't in the server!
**Usage:** clone <emoji> [name]
"""
view = discord.ui.View()
button = discord.ui.Button(
label="Download", style=discord.ButtonStyle.link, url=f"{emoji.url}"
)
view.add_item(button)
if ctx.author.guild_permissions.manage_emojis:
add_button = AddEmojiButton(
emoji,
ctx,
name,
label="Add To Server",
style=discord.ButtonStyle.primary,
)
view.add_item(add_button)
await ctx.send(emoji.url, view=view)```
How can you allow emoji to support links too..? but also support discord.PartialEmoji?
i have a guide about clustering if you need it
at least, that's what a "friend" of mine does for his bot
sure that would be cool planning to write a bunch of guides once i figure out the stuff myself
send it in devconnect
message_lines.append(f"Game: {game_name}, Whitelisted: {whitelisted}, Discord Mention: {}, Discord ID: {discord_id}")
How can I place the user's mention using the user's Discord ID?
<@id>
That feels way to simple 🤣
Was expecting some nautical line haha
lol
Is there a limit to how many apps can be in a team?
this isnt tachinally related, but im curious can you not use emojis with weebhooks anymore? im trying to make a webhook with emojis. but it wont let me. seems like its not supported? any alternatives
i just made my own embed and when i do the emoji it just sends as the name. its in my serverf
how can i make it send emojis in webhook/embed builder?
Yeah you can't anymore
stupid asf
Guess you could make the webhook using your user account though
discord always gotta remove some dope shit
I think they respect the crator's emoji list?
i saw people use ticket bot for it, but i like to use my own bots
do you happen to know the format? i seen other ppl doing it with bots in discord servers.
idk if its stil <::>
That's the one
Discord will remove the format if your bot doesn't have access to the emoji of course. That's what is going on currently. But the format has not changed.
odd then. for me it doesnt work in embeds. for anything. although other servers are? im using their same bot too
not sure why discord gotta make my life so HARD
Anyone know how to code a script so staff members can manage their shift?
"Staff members", "manage", and "shift" are all not discord native concepts that you'll have to define what they mean
This is however limited to 25 options or so, correct? Is there any way to bypass this or to have multiple select menus with a different set of 25 roles?
you can't bypass that and iirc you can't either choose the roles to display
just found out you can type in the damn thing to filter results 😭
yeah
that's the same for User select menus
what could be the reason for sending 3 messages at a time on executing a command in a particular server?
Like if I use snipe command it replies thrices instead of once and it only happens with that particular server RARELY
same in case of welcomer, sometimes it sends 3 welcome message and sometimes 2 and sometimes 1
when the bot was newly added there it used to send welcome message thrice everytime but these days it has reduced and it only happens with that server and no other server.
discord.py v2.3.2
does this happen for every command and event
I have only noticed this for welcomer event and every command
is your bot hosted on a vps Or anywhere else?
DigitalOcean VPS
no double hosting
did the issue start occurring after you started hosting it?
wdym
A shift manage bot?
i don't know how to make one, but know the general idea of how it should look like
I reccomend using an already existing one like trident
like did multiple messages start after you started hosting the bot
await interaction.guild.fetch_member(self.user_id).add_roles(await interaction.guild.get_role(1176333330095022101))
Would this work?
Instead of grabbing the user object and role object, storing them in variables, could I get the user objects when I invoke the add_roles command or would this not work?
fwiw you can just give add_roles a abc.Snowflake created with a discord.Object instead
also get_role is not a coro
So the above code snippet would not work?
^
it would error since you can't await a Role
ah
It'd work otherwise (probably)
I've never really worked with the snowflake thing before.
it's basically just the most slimmed down version of a discord object with only the id
hi, im having problems with modals
it does what it's supposed to, but it still says "Something went wrong" for some reason
no errors either
do i js send my code here?
oh
guys quick question, how do i remove a specific option from a Select?
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.Select.options use the options property u will get a list of options u can alter that directly or set it urself
then edit the message with the new view
yo any1 that can tell me how hard this is to do dm for more info [ pls help]
why dm
bc reason
thanks for the clarification

leo definitely knows
You can just send here lol???
ok
so like idk anything about python but im tryna make this bot its gonna like show ur yt data ur twitter data and like if u are in a like 1 of the cords: 1130674447691563098 949885234713874512 1164702469599809567 934502745799540806 878071596793868338 889555844532940821 1125049907665977344 950298999481577472 1079391058724655104 1130712939100393563 1176629172597162065 1127414115523104830 1005535080065806347 1020151586133114941 1174999989433405450 1233573788243988540 1187299258618085396 1236703778086981744 1191502660696817664 1191502660696817664 859302615547117629
so is that hard to make
I see, yeah, bots can't access that information. To access someone's connections, you need to prompt them to log in with discord with the correct scope.
mhhhhh it could tho if u have ur twitter and yt linked
Then you can access it in your website's backend and store it somewhere.
to ur discord right?
only if u get access to it via appropriate oauth scopes
As stated before, you need to use oauth to access the linked accounts, not with a bot. It is impossible using only a bot.
i have a bot that can do it but im tryna make myt own
meaning u need to make some form of discord dashboard prompting users to login
just needs to show sum public
data yk subs like tweets stuff like that
waht is that?
The way to get the linked accounts (connections)
oh ty
but like how hard is it bc idk anything about python
Not easy but probably not too hard, but it will require the knowledge of setting up a website to receive the oauth2 response
Also, that's off-topic for this channel, because it's not a discord bot.
like whats off
definitely difficult if you have no prior python knowledge
lol yes
i doubt he got the concept of what oauth is
mhhh i dont rlly lol
it would definitely require the knowledge of how to make a website so yeah, not easy lol
who?
i dont use disboard y
nvm
how do u expect to make it when u dont know shi about python 😭
annotate the command argument with discord.Role (assuming that you are using discord.py)
thank you im gonna try :)
how do i make certain roles be able to use .gen please someone help me
async def gen(ctx, amount):
key_amt = range(int(amount))
f = open("keys.txt", "a")
show_key = ''
for x in key_amt:
key = str(uuid.uuid4())
show_key += "\n" + key
f.write(key)
f.write("\n")
if len(str(show_key)) == 37:
show_key = show_key.replace('\n', '')
await ctx.send(f"Key: {show_key}")
return 0
if len(str(show_key)) > 37:
await ctx.send(f"Keys: {show_key}")
else:
await ctx.send("Somthings wrong")```
@slate swan Python
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole) if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)
@glad cradle do you know if i can filter the roles in the selection ?
you can't
you can use an autocomplete for that but you'll provide roles names, not as fancy as this one
okay thx
discord.Option --> discord.Role as the type
how can i convert this to a slash command, i dont know any other method of puring besides ctx.channel.purge
@commands.cooldown(1, 5, commands.BucketType.user)
@bot.command(aliases=get_config("purge_aliases"))
async def purge(ctx):
allowed_roles_ids = [str(role_id) for role_id in get_config("allowed_purge_roles")]
user_role_ids = [str(role.id) for role in ctx.author.roles]
if any(role_id in allowed_roles_ids for role_id in user_role_ids):
await ctx.channel.purge()
await ctx.send(f"{ctx.author.display_name}, Messages purged!", delete_after=5)
else:
await ctx.send(f"{ctx.author.display_name}, You are NOT allowed to do that!", delete_after=5)
Is there a way to get the label assigned to a forum post?
The tags? Yes
Channel.purge will purge regardless of whether it was called from a prefix or an interaction command
YouTube is the only streaming service/platform that is against Music bots correct..?
using slash commands, how do i check if the user running the command has the manage messages commands?
@commands.has_permissions(permission)
or
@app_commands.checks.has_permissions(permission)
Example:
@app_commands.checks.has_permissions(manage_messages=True)
or
@commands.has_permissions(kick_members=True)
You can check all the valid permissions here
Is it possible to use like a if function like if has-permission == True
Id recommend the way dpy does it, because then you can setup error handling, which will handle the missing permissions for you instead of you doing it yourself.
I prefer doing it myself (mainly bc I don’t know how to use the error handling lol)
You can, but don't recommend doing it that way, because you have to setup error handling for that instance. But if you just do it how dpy does it, you can do it for all instances.
Using slash command so ctx don’t work
yeah ik
interaction.author
yes it would
same way.
interaction = ctx
Oh
No no no no 😭
well like
No bro
It don’t even work
Just no
Interaction and ctx are completely different...
They are for differen't thing. Can ctx do buttons? I don't think so. Interaction can. Ctx can't do half the things interaction can do.
ye but its simpler
yes i understand that but i meant to say some people just name the parameter ctx even in slash commands
ok so just how do i the error handeling myself i want to use an if statment to check for manage_messages=True
You are probably thinking about Hybrid commands.
WHAT
being a douche doesn't help him
Dude, understand this real quick, you would have to do a check every single command, but you could just do what I said, and add error handling instead of what you are doing.
yeah ik
i need it for litterally 1 command
sorry
ONE COMMAND
my mind just went fr
thats not what i want to do
oops @vapid parcel alr sent it
@karmic oriole what are you using?
wdym
show me your command?
@commands.cooldown(1, 5, commands.BucketType.user)
@bot.tree.command(name="purge", description="Purges messages from the channel.")
async def purge(interaction: discord.Interaction):
if check for command fr:
await interaction.response.send_message("Channel purged", ephemeral=True)
await interaction.channel.purge()
else:
await interaction.response.send_message(f"You are NOT allowed to do that!", ephemeral=True)
using an error handler would be like 2 lines longer and i dont know how to use those and dont care about learning em
dis is mine
@commands.hybrid_command(name="purge", description="Purges a specified number of messages")
@commands.guild_only()
@commands.has_permissions(manage_messages=True)
async def purge(self, ctx, amount: int, *, reason: str):
if amount <= 0:
embed = discord.Embed(
title="Purge Error",
description="Please specify a valid number of messages to purge (1 or more).",
color=0xFF0000
)
await ctx.send(embed=embed, ephemeral=True)
return
elif amount > 100:
embed = discord.Embed(
title="Purge Error",
description="You can only purge up to 100 messages at a time.",
color=0xFF0000
)
await ctx.send(embed=embed, ephemeral=True)
return
try:
await ctx.send(f"Purging {amount} messages...", ephemeral=True)
deleted = await ctx.channel.purge(limit=amount)
embed = discord.Embed(
title="Purge Messages",
description=f"Purged {len(deleted)} previous messages.",
color=0x5865F2
)
embed.add_field(name="Reason", value=reason, inline=False)
embed.set_footer(text=f"By: {ctx.author.display_name}", icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)
except Exception as e:
await ctx.defer()
await ctx.send(f"An error occurred: {e}")
@commands.cooldown(1, 5, commands.BucketType.user)
@bot.tree.command(name="purge", description="Purges messages from the channel.")
async def purge(interaction: discord.Interaction):
if interaction.user.has_guild_permissions(manage_messages=True):
await interaction.response.send_message("Channel purged", ephemeral=True)
await interaction.channel.purge()
else:
await interaction.response.send_message(f"You are NOT allowed to do that!", ephemeral=True)```
woah
boom
there you go
just use the @commands.has_permissions(manage_messages=True) decorator
thankyou lol
NO
He could also use the decorator yes. But idk why he isn't 
Why not?
CUZ I SAID
i broke it or som
Traceback (most recent call last):
File "C:\Users\gabri\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\gabri\OneDrive\Documents\vscode\discordbot\discordbot.py", line 75, in purge
if interaction.user.has_guild_permissions(manage_messages=True):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'has_guild_permissions'. Did you mean: 'guild_permissions'?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gabri\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\gabri\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Member' object has no attribute 'has_guild_permissions'
Damn calm down its simpler i thought you liked simpler things
good idea
simpler
ok i read it this time
File "c:\Users\gabri\OneDrive\Documents\vscode\discordbot\discordbot.py", line 75, in purge
if interaction.user.guild_permissions(manage_messages=True):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Permissions' object is not callable
still dont know

THEN USE THE DANG DECORATOR
I DONT WANT TO
@commands.cooldown(1, 5, commands.BucketType.user)
@bot.tree.command(name="purge", description="Purges messages from the channel.")
async def purge(interaction: discord.Interaction):
if interaction.user.guild_permissions.manage_messages:
await interaction.response.send_message("Channel purged", ephemeral=True)
await interaction.channel.purge()
else:
await interaction.response.send_message(f"You are NOT allowed to do that!", ephemeral=True)```
ITS BETTER AND ""simpler""
shutup desu
it worked :D
I'm a decorator fanatic
Wild
Fr custom decoraters too 😍
fr, bro.
YouTube is the only streaming service/platform that is against Music bots correct..?
pretty sure that Spotify is against that too, you can read the terms of service
everything except SoundCloud
Don't use music bots overall
💀
Just get a subscription. You can listen along with others with superior audio quality and more control
does anyone have a bot like this
Anyone?
Ask AI
bruh ok
Can I have some help In my post?
@vale wing
Please don't use AI to help, elaborate your answers yourself.
Do you have any on_message listeners (either via bot.listen or commands.Cog.listener)?
!rule 10
Worse
Hello, I have an Anti-nuke system but it is spamming once the nuker is banned
if len(self.author_msg_times3[author_id]) > self.max_msg_per_window:
key3 = f'antinuke:{message.guild.id}'
exists = await self.check_exists(key3)
if exists:
await message.guild.ban(author, reason="nuking the server")
embed = discord.Embed(title="User Banned", description=f"{author.mention} has been banned", color=discord.Color.blue())
print(f"spam channel detected: {message.guild.id}")
await message.delete()
embed.add_field(name="Reason", value="Tried to Nuke the server")
log = await self.bot.redis.get(f"logs:{str(message.guild.id)}")
log2 = int(log)
logging_channel = self.bot.get_channel(log2) or await self.bot.fetch_channel(log2)
await logging_channel.send(embed=embed)
Its spamming the await logging_channel.send(embed=embed)
you'll need to show more code
what can i add to the code to stop the spam?
because once i sent 'test', it started spamming and not sending it only once
add an if statement that checks whether the message author is a bot or the bot and return
like what
Hey, I'm using discord.ffmpegpcmaudio to stream audio in a voice channel. Is there any way to figure out when the audio has stopped playing? Like an event or such?
the after parameter of play()
!d discord.VoiceClient.play
Why is this showing the master branch docs? 
here are the docs for the pypi release of discord.py (v2.3.2) which don't include the things added in 2.4
thanks
hello
!d discord.VoiceClient.play
play(source, *, after=None, application='audio', bitrate=128, fec=True, expected_packet_loss=0.15, bandwidth='full', signal_type='auto')```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource).
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.
Extra parameters may be passed to the internal opus encoder if a PCM based source is used. Otherwise, they are ignored.
Changed in version 2.0: Instead of writing to `sys.stderr`, the library’s logger is used.
Changed in version 2.4: Added encoder parameters as keyword arguments.
thanks
i tried to pass in a coroutine preceded by await, but then it was executed immediately before the audio even started playing.
Hiii, anyone know how to remove this command ? The command is not anymore in my code and i have put a new command but the new don't display and the old don't delete
the command is deleted since 1 weeks
it should just need to reinitialize, when it didnt work for me i just deleted and recreated the bot from discord developer page entirly
and make sure you have somthing like this
@bot.event
async def on_ready():
print(f"Running as {bot.user.name}")
try:
synced = await bot.tree.sync()
print(f"synced {len(synced)} command(s)")
except Exception as e:
print(e)
yes but i can't make a new bot when this one is on Taylor Swift France server
and i do that
@bot.event
async def setup_hook():
await bot.add_cog(cog)```
i try to add the sync in my on_ready
i have forget that
just try the method i sent, i dont use setup_hook() so :/
Now he don't found any command 😦
but the command work with the prefix
i know why
my fault
lol
Ok everythings was just because i don't have put the correct arguments
thanks for the help
Any other ways to do it?
"Channel" + ("s" if len(channel_ids) > 1 else "")
It works, but how does that affect the code to not make the bot spam?
Im confused
Hi guys, I could really use some help here if anyone is available. Thanks!
https://discord.com/channels/267624335836053506/1243954019370664037
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{client.guilds} servers"))
i am trying to display how many servers the discord bot is in, in google i found you can use client.guilds, the problem is that client isn't defined
Traceback (most recent call last):
File "C:\Users\gabri\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\gabri\OneDrive\Documents\vscode\discordbot\bot.py", line 13, in on_ready
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{client.guilds} servers"))
^^^^^^
NameError: name 'client' is not defined
i also need it to update every once in a while
Change client.guilds to bot.guilds
You defined your client as bot so u need to use bot
Ok
I’m making had to use len() for anyone who sees this and needs the same thing
hello
i have a problem
Eu estou estudando recentemente sobre o Discord.py.
Estou querendo pegar o id do usuario que utilizar "!myid", mas não estou conseguindo. Meu código é esse:
@bot.command(name="myid&...
😟
author?
yes
where?
@bot.command(name:"myid")
async def id_user(ctx, user: discord.Member):
await ctx.send(user.id)
remove user: discord.Member e troca user.id em ctx.send para ctx.author.id
he was! thank you very much.
this documentation is confusing
How do I delete the bots own message?
Same way you delete any message, calling .delete() on it
Can you give an example?
because ctx.message.delete() wouldnt even work on the bots own message
In a .send or .reply?
send
thanks
it's same for both
I meant it as send/reply
in a respond it would be different, but yeah prefixed commands are the same
The on_message is activated whenever a message is sent even if the message is from the bot
in slash response.send_messagethere is also a delete_after kwarg
please, I know
Next thing you're going to tell me is there's one in ui.View 🤣
maybe..
lol
like, if i didn't knew dpy internals
yo guys, how do you have different profile pictures for yout bot across different discord servers?
You can't
Bots that do this don't just send an http request
some server made a rip off bot, my bad
another question, whats the best option to host your discord bot?
entirely depends on what your needs are . discord bots aren't a single monolith that all behave the same way
what are the different needs?
like what services are good for what purposes
Depends on what the bot is doing. What resources it requires
How do you install PM2?
Im making a bot mainly for currency keeping, it uses sqlite3 as its database
Do you know how to add PM2?
Do you know the resource usage of your bot? Primarily memory and cpu
whats that?
its not that intensive
Look It up and I found how to.
wasnt that a js module
what does that do
run the bot and stuff from the shell and see ur files from anywhere.
if you know what that does why dont you just search how to install it
does it run while my pc is off?
I did I was being stupid.
some PCs allow this, but if the PC is off all the processes (well.. most of them) are killed
Do embeds really not support discord.Files..?
Killed In action 🫡
They actually can
How..?
I was thinking about hosting it on some server somewhere if its affordable or someth
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
Note that the filename in the File constructor and the filename in the URL must match, and must be alphanumeric.
*From the discord.py server*
I am trying to set the file in the set_image but using discord.Files
If you put pc Is always on option then u can do that It host on your pc you dont have to pay anything apart from power bills.
But I live with my parents so no problem for me.
my parents dont like my pc being on all day when im ni school :p
Yeah but there is no url to the file I am trying to use, so I can't just set it in the set_image.
So basically the embed can't use it
wait, can the bot run on someone elses pc if I send them a converted exe file?
It literally shows how the url must be lol
attachment://your_file_name.extension
erm
if they have the deps yeah
How can I use proxies with aiohttp?
Oh so the bot was sending its own message content
Makes sense
lets say i have a slash command in a cog (also a sub command) how would i be able to make it a normal command as well
does anybody have a bot like this
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Hello, I have an Anti-nuke system but it is spamming once the nuker is banned
Its spamming the await logging_channel.send(embed=embed)
How is someone adding channels "nuking" the server
someone with the manage channels permission*
they spamming the channels\
And if someone legitimately needs to make a couple of channels for an event or something and your bot randomly bans them out of nowhere?
lol
the bot deemed them not worthy
wdym?
Him be like:
Anyone knows how to use insomnia to keep typing forever like NTTS and break discord ToS
Can I have some help In my post?
which post?
Idk how ot get link and acording to them idk basic Python 💀
uhh where is it
Just look for one made by me.
in #1035199133436354600 ?
Yes.
the links in this pin lead to a 404 ;-;
See https://about.abstractumbra.dev/dpy for now
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Thanks 🙏
https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/
this guide looks way better
A hands-on guide to Discord.py
yepp its pretty good and concise, got what i wanted to look for (options in slash commands), thanks for sharing
Hi i'm on a adkynet server python and i have this error but everything is import somebody have a idea ?
CONSOLE:
ERROR: Could not find a version that satisfies the requirement json (from versions: none)
ERROR: No matching distribution found for json
WARNING: There was an error checking the latest version of pip.
Traceback (most recent call last):
File "/home/container/maine.py", line 4, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
container@pterodactyl~ Server marked as offline...
[AdKyNet SAS Daemon]: ---------- Detected server process in a crashed state! ----------
[AdKyNet SAS Daemon]: Exit code: 1
[AdKyNet SAS Daemon]: Out of memory: false
[AdKyNet SAS Daemon]: Aborting automatic restart, last crash occurred less than 60 seconds ago.
You don't have a discord library installed on this python installation
i have install that the problems
How?
in requirement file and with import because the file is on a server
Putting things in a requirements file doesn't do anything on its own
Unless something installs from that file, and then you run python from that same installation
Additional Python packages
python-dotenv discord asyncio load_dotenv discord-ext-bot discord.gateway PyNaCl Numpy datetime json
Install additional python packages. Use spaces to separate
i have the same error with that
then i have change for requirement file
it was still working a few days ago without touching anything

Is this one of those shitty panels that doesn't actually let you hit the command line?
its a free server because i dont have money i'm young
Does any one have a free nuke bot
There are student credits you can apply for
A host that doesn't let you access the command line is honestly just going to get in your way, good luck though
Want to elaborate on what this means and what you're trying to accomplish?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
#bot-commands

nuke bot?
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
What is different between await message.author.edit(timed_out_until=timeout_time) and await timeout(until, /, *, reason=None)
!rule 1 :)
1. Follow the Python Discord Code of Conduct.
!ban 1230851876929667143 30D You have to follow our rules if you wish to participate in our server. If you do rejoin the server after your ban is over, make sure you've read our rules carefully.
:incoming_envelope: :ok_hand: applied ban to @stuck hare until <t:1719324347:f> (30 days).
thanks vivek
not a much difference
most likely that .timeout looks more obvious what it does when you read code after 1 year
but for example
if you were to change user nickname when he is timed out
you could use one line of code (.edit(nick="MUTED | ...", timed_out_until=...)) and not two (.edit(...); .timeout(...))
So is not that await timeout was implemented later?
Okay. I see the logic here
doubt it
