#discord-bots
1 messages · Page 249 of 1
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Show full error
@bot.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name = "Civilian")
await member.add_roles(role)
channel = bot.get_channel(1091042545133437015)
em=discord.Embed(
title=f"Welcome",
description=f"{member.mention} Joined {member.guild.name}",
color=discord.Color.random()
).add_field(
name=f":wave: Rules",
value=f"[#1091042549273202738](/guild/267624335836053506/channel/1091042549273202738/)"
).add_field(
name=f":wave: Chat",
value="[#1091042550078525518](/guild/267624335836053506/channel/1091042550078525518/)"
).add_field(
name=f"Total members",
value=f'{member.guild.member_count}'
).set_footer(text=f"{member.name} just joined")
await channel.send(embed=em)
Correct me if I'm wrong, but that's not the error
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 293, in on_member_join
await channel.send(embed=em)
AttributeError: 'NoneType' object has no attribute 'send'
channel is None
channel = bot.get_channel(1091042545133437015) returns None
So it could not find channel with id you provided
Or it's not cached
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
Try using this
channel = bot.get_channel(1091042545133437015) or await bot.fetch_channel(1091042545133437015)
Is usually something you'd do
It first tries to get it from cache, if it's not found it will make the API call with fetch
alright
if i have a command like !onduty that gives a user the on duty role and the !offduty that gives a user the off duty role
and the user runs !onduty while having the off duty roles
how to make it to remove the role
You know this exists right? Especially for such basic questions
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
i pretty cant understand the way docs explain it
if author.has_role("Off-duty"):
await author.remove_role("Off-duty")
you can understand the docs when you properly understand how classes and objects work
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 233, in onduty
await author.add_roles("🟢On Duty")
NameError: name 'author' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'author' is not defined
The error tells you what's wrong. You haven't defined author.
how should i call it?
ctx.author
!d discord.ext.commands.Context.author Use this if you want to get the author of a command.
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
Be mindful that it will return a User instead of a Member under certain circumstances, and Users don't have any attributes/methods relating to guild roles.
i have this error now
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 233, in onduty
await discord.ext.commands.Context.author.add_roles("🟢On Duty")
AttributeError: '_cached_property' object has no attribute 'add_roles'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: '_cached_property' object has no attribute 'add_roles'
If you're unable to comprehend documentation, just google and look at stackoverflow
It's an attribute of a commands.Context instance, not the class itself
OOP moment
Usually it's called ctx
.
.
or just learn how to comprehend documentation??
stackoverflow often has outdated answers
Yeah you learn him real quick
Not for this
Love your profile bio by the way.
Thanks 🐈
It's better than watching YT tutorials at least
cough Lucas cough
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 233, in onduty
if ctx.author.has_role(ctx.guild.get_role(1115217285683089408)):
AttributeError: 'Member' object has no attribute 'has_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'has_role'
@bot.command()
@discord.ext.commands.has_role("Staff")
async def onduty(ctx):
if ctx.author.has_role(ctx.guild.get_role(1115217285683089408)):
await ctx.author.remove_roles(ctx.guild.get_role(1115217285683089408))
await ctx.author.add_roles(ctx.guild.get_role(1115217207811637318))
await ctx.send("Removed off duty and added on duty.")
else:
await ctx.author.add_roles(ctx.guild.get_role(1115217207811637318))
await ctx.send("Successfully gave you on-duty!")
I would send you a stack overflow link but @vocal snow wants to teach you the documentation
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.
New in version 2.0.
guys how can i fix this error?
aded.
@commands.command()
async def reload(self, context: commands.Context):
await self.bot.reload_extension(f"cogs.commands")
await context.send(f"Reloaded")
!d discord.ext.commands.Bot.reload_extension
await reload_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
You have to load the extension before you can reload it using that method 🤷
It says there in the error
its already loaded
Then the error shouldn't appear
async def setup_hook(self):
raw_exts = os.listdir("./ext")
exts = [f"ext.{ext.replace('.py','')}" for ext in raw_exts if ext.endswith(".py")]
for ext in exts:
try:
await self.load_extension(ext)
print(f"Loaded {ext}")
except Exception as e:
print(f"Failed to load {ext}: {e}")
print(f"Logged in as {self.user}")
It seems like you're loading extensions from the ext directory in this code, but you're trying to reload an extension from a directory named cogs
Isn't it obvious

oops,i dumb,soory
thanks for help
basically i have a csv file with a large amount of information and i want a discord bot that does as follows :
when i run a command like !search (input) it should search the file for that term and if found it displays it in the chat
does anyone know a bot on github that works similar to this?
Why do you want a bot from GitHub? That sounds like a fairly easy thing to implement
because i need it quite urgently as a last resort kinda thing
how easy are we talking?
Very easy
Get some CSV parser and search with it, that's about it
thanks a lot
!d csv moment 🐈
Source code: Lib/csv.py
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
That's pretty much... my point..?
Yes?
Probably more worth it mentioning them instead of me 
I use button to edit an embed but each time I have "This interaction failed". How can I remove it ?
Respond to the interaction correctly
How ?
Multiple ways, without knowing the failing code can't have an overview and can't help much either
Why interaction.channel.send instead of interaction.response.send_message?
I have already sended a response
The interaction from clicking a button is different from when a slash command is executed
You need to respond again
Okay but I just want to my button edit the embed not send text
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
edit_message is not defined
please show your code and not just say the error
Because it's on an InteractionResponse object
So you'll need to use the following first
!d discord.Interaction.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 "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "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.
Then on the returned object you can use edit, should be better
Otherwise if you have an InteractionResponse object, go ahead and use it
I'm sure that they can get one
Considering they never give code and when they give it's the most minimal code e.g. 2 lines, hard to know
My code is very ugly, it's the first time I use button. The aim is to create an embed with buttons that can modify the content of the embed.
import os
import discord
from discord.ext import commands
from discord import app_commands
from lib import minecraftclass as mc
from lib.minecraftdb import db as db
class ServerButtons(discord.ui.View):
def __init__(self, interaction):
super().__init__()
self.interaction = interaction
async def send(self, interaction):
self.message = await interaction.response.send_message(view=self)
def create_embed(self, embed):
self.embed = embed
return self.embed
@discord.ui.button(label="🔄 Lancer", style=discord.ButtonStyle.green)
async def start(self, button: discord.ui.Button, interaction: discord.Interaction):
await self.interaction.channel.send("Lancement du serveur")
class Minecraft(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.minecraftBootFiles = os.listdir('scripts/minecraft_boot')
self.minecraftBootFiles = [file.replace(".sh", "") for file in self.minecraftBootFiles]
added = [name[0] for name in db.get_all_server_names()]
bot.logger.info(str(added))
for server in self.minecraftBootFiles:
if server not in db.get_all_server_names() and server not in added:
db.add_server(server, "Serveur basé sur "+server, 0)
added.append(server)
del added
@app_commands.command(name="json", description="See configuration file")
async def json(self, ctx : discord.Integration, file: str = None, key : str = None):
if key != None:
await ctx.response.send_message(globals()[file.value].data[key], ephemeral=True)
else :
await ctx.response.send_message(globals()[file.value].data, ephemeral=True)
@app_commands.command(name="minecraft",description="Choose a minecraft servers to manage")
async def minecraftserver(self, interaction : discord.Integration):
servers = db.get_all_servers()
for server in servers:
if server[3] == 1:
serverRunning = server
else :
serverRunning = None
if serverRunning == None:
embed = discord.Embed(title="Serveur Minecraft", description="No server launched", color=0x3EFF00)
for server in db.get_all_servers():
embed.add_field(name=server[1], value=server[2], inline=True)
view = ServerButtons(interaction)
await interaction.response.send_message(embed=view.create_embed(embed), view=view)
async def setup(bot):
await bot.add_cog(Minecraft(bot))
give me a minute ill try to read it all, kinda on a small screened laptop so it looks funky haha
thank you
which response are you attempting to modify
I want modify the embed
the self.interaction.channel.send in start is just for "debug"
I Got a question
Imagine i have the command !on.
I Wanna make a code so only people that are on a SPECIFIC voice channel can run this command
how to do it?
Get their voice state channel and do a comparison
weyo
i need help
How to make a code that counts how many hours the user is on a specific voice channel
save when user joins channel and when he leaves it
and substract them
message = await interaction.response.send_message(embed=embed, view=view)
and when I
await message.edit(content="")
I've got this error : AttributeError: 'NoneType' object has no attribute 'edit'
Why my embed is a NoneType ?
send_message doesnt return the message
oh
!d discord.Interaction.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 "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "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.
get it from this
ty
Traceback (most recent call last):
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "main.py", line 228, in ticketcallback
await interaction.response.send_message("Επιλέξτε παρακάτω", view=view, ephemeral = True)
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.3: The specified option value is already used
Whats this?
The specified option value is already used
what
line 221 is
created_channels = []
guys, i'm trying to use the
@blablabla.error
async def blablabla_error(ctx, error):
if isinstance(error, commands.errors.MissingPermissions):
await ctx.send('> one message')
but when i use the commnd i have this error instead the bot send a message, someone know why?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'CommandInvokeError' object has no attribute 'missing_perms'
i'm using this in the command
@commands.has_permissions(attach_files=True)```
Use commands.MissingPermissions
How can i check if the deleted webhook from a specific channel is actually the webhook stored in our database??
same happened, looks like the:
if isinstance(error, commands.errors.CommandInvokeError):
await ctx,send()```
can send a message, but the commands.MissingPermissions cant
maybe
if isinstance(error, commands.CommandInvokeError):
if isinstance(error.original, MissingPermissions):

You literally just said the bot shows this error instead of sending a message and then you said it can
it can with commands.CommandInvokeError but not with the commands.errors.MissingPermissions or commands.MissingPermissions
not here to fix it, but I don't recommend using ctx, Interactions are more predictable tbh.
Well as first change I'd type-hint to discord.Interaction and not discord.Integration
oh, it's different ? I thought it was just the name changed
I sometimes typehint to integrations instead of interactions
first make an embed I think and then get to send it in the ctx.send() so ye
2 sec
@slate swan same prob
await?
my bad 🤣
same prob
what??
is color an int?
can you try to put it in a ""
and what's that color's name
cause you can do like
color = discord.Color.color_name() I think so
yeah but i want to make custom colors because each user wants to use different colors
interesting
can u help me ?
I'd solve it with RGB but it seems like idk hex
a
Honestly I would do
embed = discord.Embed(color=discord.Color.from_rgb(rgb))
a
what does it mean?
!d discord.Colour.from_str
classmethod from_str(value)```
Constructs a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") from a string.
The following formats are accepted...
nothing
rawe t'es 🇫🇷 toi 😂
💀
guys someone know if after i use a await guild.leave() that will call the on_guild_remove event?
just check it
run the .leave method and register the event you want to check
and see if it executes
too much work to leave a guild and then invite it back
if emoji == ('✅'):
await payload.member.add_roles(discord.Object(sample_role_1))
await payload.member.remove_roles(discord.Object(sample_role_2))
so to add and remove roles with reaction I use this, but how do I remove a role when a role is deselected instead, or is that not possible
!d discord.on_reaction_remove
discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.
Note
To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").
This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Note
Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload) -> None:
if verify_message_id == payload.message_id:
emoji = payload.emoji.name
if emoji == (verify_emoji):
await payload.member.add_roles(discord.Object(verify_role))
this is how I add it,
with on_raw_reaction_remove, there is no member attribute, how would I apply it to the on_raw_reaction_remove?
Probably
yes
anyone know how i can get the invite code a member used to join using dpy?
you can't, you have to store how many uses each invite has and see which invite increases when a member joins
how do I restart a websocket connection in a voice call
It's thread safe but you should ask this in #async-and-concurrency
This channel for discord bots
can someone confirm on something please: https://discord.com/channels/267624335836053506/1115464479380086864
How do you get a bot to join a voice channel? In this specific case I want the bot to join the same VC as a certain user, play an mp3, then leave
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
What specifically do I need to import from PyNaCl? Everytime I try to import it PyCharm just says no module found even though the package is installed
also this is a discord bots channel
so basically im trying to run a discord bot 24/7 so I purchased a vps but when I installed python and tried to run the bot it js said mdules installed
What are you importing it for
if anybody is avail to help this is my issue
Microsoft Windows [Version 10.0.20348.1129]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Administrator\Desktop\test bot>py main.py
Exception when importing modules
Installing necessary modules....
'pip3' is not recognized as an internal or external command,
operable program or batch file.
'pip3' is not recognized as an internal or external command,
operable program or batch file.
'pip3' is not recognized as an internal or external command,
operable program or batch file.
Modules installed!
C:\Users\Administrator\Desktop\test bot>
yes I am
i bought the windows version on vibegames because thats what my friend told me to do
dang it
use linux
what's the diff
also why are you using a game host for a VPS
:|
im very new to this
idk ngl im js doing what my friend told me to do
Did you install pip?
i need to host my bot b4 i go on vaca
i might have, whats the command to do so
@client.tree.command(name="random-number-button", description="sends a random number choose a number e.g 1 10 in a button")
async def randomnumberbutton(interaction: discord.Interaction, number1: int, number2: int):
button = Button(label=f"Random number from {number1} to {number2}", style=discord.ButtonStyle.primary)
channel = client.get_channel(1112053260879147130)
async def button_callback(interaction):
try:
await interaction.response.send_message(random.randint(number1, number2))
await channel.send(f"random number button clicked by {interaction.user}")
except:
channel2 = client.get_channel(1112053260879147130)
await interaction.response.send_message("error: number1 needs to be bigger than number2")
await channel2.send(f"random-number-button clicked by {interaction.user} but an error occured")
button.callback = button_callback
view = View()
view.add_item(button)
await interaction.response.send_message(f"Click the button to get a random number from {number1} to {number2}", view=view)
await channel.send(f"random-number-button command used by {interaction.user}")
``` how can i make it so when a user clicks it a certain amount of times disable the button
add a counter and check if counter > some number
ok
why not just subclass a view
class CounterView(View):
MAX_VALUE = 5
def __init__(self, *, timeout: int) -> None:
super().__init__(timeout=timeout)
self.counter = 0
@discord.ui.button(label="0", custom_id="button")
async def button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
self.counter += 1
button.label = self.counter
await interaction.edit_original_response(view=self)
if self.counter >= MAX_VALUE:
for item in self.children:
item.disabled = True
nah
what do you mean nah
i dont use classes
Why
What
i'm guessing you don't know how
yeah
could you show me how to do it without class
no
Why not learning classes instead, it's a fundamental knowledge you should have - especially for discord.py
Not rocket science either, takes a few minutes to at least understand the basics and then with the time you'll learn more
i literally already gave you the working code with classes 
Could i just disable it when clicked?
I'm trying to get a discord bot to automatically leave after a certain duration, but this is an event not command since the bot automatically joins the channel when a specified user joins a voice channel, how do I set that up?
Currently have :
@client.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel and member.id == config.ashy_id:
await discord.VoiceChannel.connect(after.channel, timeout=30, reconnect=True, self_deaf=False, self_mute=False) # Bot Joins Channel that the specified user joins
time.sleep(2) # the duration doesn't matter here
# Need to Disconnect Here
The joining works fine, but I can't get the leaving to
That... isn't how OOP works
The entire
await discord.VoiceChannel.connect(after.channel, timeout=30, reconnect=True, self_deaf=False, self_mute=False)
line is wrong
It may work apparently, but it's wrong
Please explain?
In the documentation when you see something like discord.VoiceChannel.method() it means you're calling method on a discord.VoiceChannel object
Now with your event, you have the member, before and after parameters
I'm still super new to python, so sorry if I say something super dumb
You've already used before.channel and after.channel
Which areeeee
!d discord.VoiceState.channel
The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
Got it, I've changed the line
Thank you for the explanation
Disconnect is a bit different
You'll need to use the voice_clients attribute in your bot
In your case bot seems to be client
You are correct
It will give you a list of voice connections
There you can iterate over them and check the channel and/or guild IDs to see if they match the channel and/or guild IDs you want your bot to leave
Normally you just need to check the channel ID
Or I think you can just use await member.guild.voice_client.disconnect()
Not sure if that will work correctly, never really used voice channels in the past
client.voice_clients and member.guild.voice_client both give the same output, and await member.guild.voice_client.disconnect() does in-fact make it leave the voice channel; tysm! This is helping me significantly
Now I just need to get it to play an mp3 before it leaves
No problem and for that I have no idea 
RIP, I'm so screwed
it's pretty simple
you need to create an ffmpegpcmaudio
you need to install ffmpeg though
Can PyCharm do that or do I do it manually?
it's not a python package
Got it
https://ffmpeg.org it's an executable
I swear they were there during first md extension update
https://support.discord.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline- they are supposed to be there tho
Want to inject some flavor into your everyday text chat? You're in luck! Discord uses Markdown, a simple plain text formatting system that'll help you make your sentences stand out. Here's how to d...
Does it display correctly on desktop
no
no
😭
it works on canary prolly
Well I believe I got ffmpeg installed onto my system properly ffmpeg in cmd prompt results in (also yes I know cringe Windows, I'm currently working on switching over to Linux soon)
ffmpeg version 2023-05-31-git-baa9fccf8d-full_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
built with gcc 12.2.0 (Rev10, Built by MSYS2 project)
configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libaribb24 --enable-libaribcaption --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libjxl --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-liblensfun --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libvpl --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libcodec2 --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
libavutil 58. 12.100 / 58. 12.100
libavcodec 60. 16.100 / 60. 16.100
libavformat 60. 5.100 / 60. 5.100
libavdevice 60. 2.100 / 60. 2.100
libavfilter 9. 8.101 / 9. 8.101
libswscale 7. 3.100 / 7. 3.100
libswresample 4. 11.100 / 4. 11.100
libpostproc 57. 2.100 / 57. 2.100
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...
Though pycharm still says its missing, what do I need to do so PyCharm can use it?
what do you mean pycharm says it's missing, pycharm won't know if it's missing or not
if you're importing it you're doing it wrong
I've never used ffmpeg, I just installed it, its not being imported and even when I do so it doesn't work. The error is discord.errors.ClientException: ffmpeg was not found. or more specifically
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\state.py", line 158, in logging_coroutine
await coroutine
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\voice_client.py", line 337, in on_voice_server_update
await self.ws.close(4000)
^^^^^^^^^^^^^
AttributeError: '_MissingSentinel' object has no attribute 'close'
2023-06-06 03:29:34 ERROR discord.client Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ashy\Desktop\PythonProgramming\exodusAutomatonDiPy\bot.py", line 131, in on_voice_state_update
audio_source = discord.FFmpegPCMAudio('spooder.mp3')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py", line 289, in __init__
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py", line 166, in __init__
self._process = self._spawn_process(args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py", line 183, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.
I added it there, or atleast thought I did
and add the path to the executable in the path variable
Nope they entirely removed it and they don't know when and if they will even bring it back
Should it just be C:\ffmpeg ?
mh sad
a
ok
did you download the exe
Yes
huh how do i have ffmpeg but i didn't install it
I downloaded ffmpeg-2023-05-31-git-baa9fccf8d-full_build.7z and ran the exe inside
as well as have the folder for ffmpeg in C:\
ah i have it from scoop
It also responds in cmd prompt
where is the ffmpeg.exe
C:\ffmpeg\bin\ffmpeg.exe
extract it
I did
ok
This is going to make me sound even more stupid, how do I get to that? I've never had to alter that until now
nevermind
also PYTHONUNBUFFERED=1 is already there, do I just add a , between or just remove it?
Alright, it now knows where ffmpeg is and can use it cool, but shit my code doesn't work
Whats the proper way to get the bot to play a specified mp3?
create a new FFmpegPCMAudio
then i think you can just pass it to voice_client.play
@clear lark you need to create a new ffmpegpcmaudio
like i said
also discord.Client.voice_client does not exist
I would make a new ffmpegpcaudio by?
Yes
I was being dumb and reading https://discordpy.readthedocs.io/en/latest/api.html#ffmpegopusaudio
Correction: I'm being dumb, and am failing at python
cool
I'm now getting
Traceback (most recent call last):
File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ashy\Desktop\PythonProgramming\exodusAutomatonDiPy\bot.py", line 132, in on_voice_state_update
voice_client.play(player)
^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.voice_client' has no attribute 'play'
2023-06-06 04:06:42 INFO discord.player ffmpeg process 17456 has not terminated. Waiting to terminate...
2023-06-06 04:06:42 INFO discord.player ffmpeg process 17456 should have terminated with a return code of 1.
and here is what the event looks like
@client.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel and member.id == config.ashy_id:
await after.channel.connect()
# problem child
sound_file = 'spooder.mp3'
player = discord.FFmpegPCMAudio(sound_file)
voice_client.play(player)
# problem child
time.sleep(2)
await member.guild.voice_client.disconnect()
voice_client.play(player)
voice_client is supposed to be an instance of discord.VoiceClient
not the discord.voice_client module
don't import voice_client
VoiceChannel.connect returns a VoiceClient object, you can get it from that
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
This is what you think
apparently it was such a funny joke everyone skipped over it
can someone help me lol https://paste.pythondiscord.com/raw/wisowuyuna
don't be rude to snipy 😔
The command help is already an existing command or alias.
discord.py includes a default help command
you have to pass help_command=None to the bot
Either remove the existing help command or subclass it
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
alr
no subclassing sucks
wasn't that hard to tell it was a joke
That feels like just a way to get over something lmfao
"It's just a joke, I wasn't really meaning it"
shut up little child
we know it
VoiceClient.play(source=player) results in TypeError: VoiceClient.play() missing 1 required positional argument: 'self'
its not static method
you need to gather instance of VoiceClient
most likely from guild.voice_client
you need an instance of VoiceClient which is returned by the connect() call you did earlier
or from connect
didn't you just make this mistake 30 minutes ago
most likely yeah
I've been awake way too long and am barely functioning, but I need to finish this
I've only touched python for a couple of days now, if it wasn't obvious, and I'm still lost on how to get the instance of VoiceClient from connect() as I just keep getting AttributeError: 'VoiceChannel' object has no attribute 'is_connected'
well, connect() does not return a VoiceClient instance
!d discord.Guild.voice_client does
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
So this is wrong? and won't give me an instance of VoiceClient
it does
well it returns VoiceProtocol, but for most cases that is VoiceClient
So I do I get it to the self={instance here} ?
💀 the docs suck
yeah im not sure when it doesn't return VoiceClient
This is an abstract class. The library provides a concrete implementation under VoiceClient.
Okay, for simplicity, what does
THIS
sound_file = 'spooder.mp3'
player = discord.FFmpegPCMAudio(sound_file)
VoiceClient.play(source=player, self=VoiceProtocol)
need to be to function, so I can see what it needs to be so I can see what I'm doing wrong
☠️
its not static method
I've changed that third line so many times I don't know what to do with it anymore
i feel like the typing could have been much better
and passing self as class makes no sense at all
you'd have to use a Context or Guild instance in order to use that
ctx: Context
ctx.voice_client.play()
you know what instance methods are?
Its an event, not command, or am I just dumb and ctx works here
or at least what instance is
too good for the devs
use the Guild instance then
guild: discord.Guild
guild.voice_client.play()
💀
they will copy this word for word
not completely honestly, again I am super new to Python & programming as a whole. I'm only making a discord bot because It gives me tangiable results and I can make it do things I want it to do for things I do often
oh wait when did they give reaction perms here 💀
recently
and then discord added this super reaction nonsense so they might take it away again
for more than a month acffftually
you're an old cat
granny
usually we recommend learning python basics before making a discord bot since it is quite a complex project for beginners, but essentially you need to first get a VoiceClient object, and then call play on it; ```py
voice_client = await after.channel.connect()
voice_client.play(...)
stop passing self
I was only passing self since it kept giving me errors saying I needed it, likely because Iwas just wrong in the first place
yes because you only use Class.method() for when it's a staticmethod or classmethod
in other cases you need an object
Classes are used to create objects that have specific behavior.
Every object in python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.
Here is an example class:
class Foo:
def __init__(self, somedata):
self.my_attrib = somedata
def show(self):
print(self.my_attrib)
To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.
bar = Foo('data')
bar.show()
We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.
they're literally new to python, dont expect beginners to understand those complicated terms too 💀
I've literally only started python about 4 or 5 days ago at this point, and before then I knew a bit of javascript
AClass().foo()
# is not equal to
AClass.foo()
learn basic python and basic OOP then before starting a discord bot its not good project for someone who just started
Any recommendations on where to learn basic python? (sure thats the 7000th time you've heard that question) Also Snipy you very very correct
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I'll go through that tmrw, but I'm going to go to bed since its late here, night yall, and thank you so, so, so, SO, much for dealing with my stupidity and helping me.
And here is what I finally ended on, which does work as intended
@client.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel and member.id == config.muw_id:
sound_file = 'spooder.mp3'
voice_client = await after.channel.connect()
voice_client.play(discord.FFmpegPCMAudio(sound_file))
await asyncio.sleep(2.5) # was time.sleep(2.5)
await member.guild.voice_client.disconnect()
There is mostly likely something wrong with it (besides error handling), but I do not care enough to fix it until I learn more
👍 but never use time.sleep() in a discord bot or any async code it is blocking use await asyncio.sleep() instead
What other fun community commands should I add
sometimes chatgpt is a good source
I wanna make black tea command but idk how
wait_for and max_concurrency
i dont even know what that is
a word speed game
The game that is like u have to have a word with a random 3 letters
like TEA are the letters and teacher has those letters
what does that do?
noted
?
unfortunately we are not mind readers
What do you mean?
i have noted the fact that you need help
you have to tell us what you need help with
Ok
lmaoo
Wait
``import discord
from discord.ext import commands
import os
client = discord.Client(commands_prefix="s")
@client.event
async def on_ready():
print("online")
@client.event
async def begin(ctx):
await ctx.send("lets start")
my_secret = os.environ['Token']
client. run(my_secret)``
This is my code
But why it not send any message by commands
sbegin
?
@smoky sinew
Because you haven't made any commands
clients cannot have commands only bots
maybe because you put commands_prefix
Consider reading the error
My thing crashes sometimes in a voice call will restarting the ws connection work
I will send the error
Your script crashes?
noted
or maybe fix the crash
Does it crash with an error?
I will check because Im not home rn
I dont think it does it just cuts
``Traceback (most recent call last):
File "main.py", line 5, in <module>
bot = discord.Bot(commands_prefix="s")
AttributeError: module 'discord' has no attribute 'Bot',``
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
I didn't under stand
I think restarting the ws connection will work because it recreates a new user with a new ssrc and audio data
do not
Mb
Can any one please copy this code and send it to me because I'm in phone
I was on 1.7.3 and it fixed mine
.
wth you're not supposed to copy that thing
I didnt understand what should I do and no one replyng to me
do you know python basics?
I have error with
@client.command()
You tell me to make it bot not client
And i made it but there is another problem happend
what error
This is it
because discord.Bot doesn't exist like the error says
this is the class
I need to know how i make prefix to my bot
you set the prefix in the commands.Bot constructor
please read
as well as the commands extension doc: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
Were is the error bere
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
@vocal snow
the error is that discord.Bot does not exist
What should I replace it with
how many times do you need us to repeat
I will try
and please read the doc first
Finally its worked
used to be there I think they changed it
@vocal snow
I have another question
But it is very simple
How can I make the bot send the message in spasific channel
never in discord.py
get the channel with bot.get_channel, then use channel.send
discord.Webhook.partial is a function
I will try
if you're trying to construct a webhook from it's url just call Webhook.from_url
run your code and see if it works
This is how I will enter into many mazes for a new ni
I do not speak English fluently
2 member objects, one for partner one for author
Looking for a person who will develop a script in python I PAY
!rule 9
i pay
Reading may help, let me put it in bold just for you
Do not offer or ask for paid work of any kind
You've been told so many times as well that it's not allowed
thank u
Where did Member.permissions go? Do I need to walk through Member.roles instead?
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
Oh my god - I'm blind. Thanks.

my bot turned on for the first time but it didnt load the rest of the commands
What library are you using
If it's discord.py, you should await the bot.load_extention methods
you should just iterate over every file in your commands folder and if it ends with .py load it instead of doing what youre doing
Also cogs are not meant to be one per command but rather one per category which contains multiple commands
Two member objects yeah
One that corresponds to the author and another one to the partner

how can i disable a button?
!d discord.ui.Button.disabled
property disabled```
Whether the button is disabled or not.
^
Set this to True/False then edit your message with the new view
Because there's no code to copy paste
You set disabled of your button to True/False as already mentioned
so is it py disabled = True
On your button, yes
Just doing disabled = True will create a new variable which is not what you want, you want to edit that attribute from a button
Here once again, learning OOP basics would be helpful
oml lol
disabled = True
button.disabled = disabled
😳
@slate swanis scameur
Hey so I tried hosting my bot on a server, and since it's been added to a big server it is having a lot of issues starting
Even if it gets going it's taking around 1 GB of memory which doesn't make sense it shouldn't, and it didn't when we hosted it while it wasn't in the big server
Is there something we need to do to make it work properly while being in a big server?
I assume it gets a lot of on_message events before even starting up properly or something?
This is the code: https://paste.pythondiscord.com/hatemaresu
Hi I have a question I am using slash commands but the int in the option of the slash command won't take a decimal how do I make it take the decimal?
make it a float instead of int
so it it is amount: float
yes
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
});
const prefix = '!';
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on('messageCreate', async (message) => {
if (message.content.startsWith(prefix) && !message.author.bot) {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'team') {
try {
const response = await axios.get('https://ctftime.org/api/v1/teams/227975/');
const teamData = response.data;
const embed = {
title: teamData.name,
description: `Country: ${teamData.country}\nPrimary Alias: ${teamData.primary_alias}`,
thumbnail: { url: teamData.logo },
fields: [],
};
for (const year in teamData.rating) {
const place = teamData.rating[year].country_place;
if (place) {
embed.fields.push({ name: year, value: `Country Place: ${place}`, inline: true });
}
}
message.channel.send({ embeds: [embed] });
} catch (error) {
console.error('Failed to fetch team data:', error);
message.channel.send('Failed to fetch team data. Please try again later.');
}
}
}
});
client.login(process.env.token);
i am trying to get informations from json format api
thats java
using axios but it shows this
thats javascript not python
oh
thats java
sorry where is the js room
java and javascript are different fyi
i was thinking that discord bots for all languages
this is a python discord server
oh
i know but i was thinking is a discord bots room in general not for only python sorry
your missing intents
what exactly i have to do?
intents.members = True
intents.message_content = True
client = discord.Client(intents=intents)```
that should work
but discord.Client is different from my bot = commands.Bot
so give that a try and see what happens
smh the debugger is already pointing where you should put it: before the client object creation
and now says name 'intents' is not defined
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Could anyone please help out in #1115717181729148970 message
Already got closed once because no answer 
Start by not enabling all intents
Alright
But just curious as to why it happens only here, I have another bot with a lot more stuff happening that's only taking 60MB of storage
- it has all intents enabled too
I'll just post it here since the post keeps closing
I made a Discord bot that tracks the activity of specific individuals that are specified on a database.
This ran fine while testing I tried to spam it too, didn't have any problems but once I got it into the big server it was going to be used in, it was not starting up properly, kept crashing and was using extreme amounts of CPU power and Memory.
After implementing the Event Queue it seemed to be a little better, still a lot of CPU usage on startup but it was fine afterwards. For some reason it still takes up 950MB of memory on the server and I am not sure why.
Any help would be much appreciated, thanks
as someone has already said you're caching everything because you're using discord.Intents.all() i suggest to enable only the intents that you need so the library won't cache things that you don't use
alright will try that
My other bot is also doing all but only using 60MB of Memory, that's what I find weird
Alright I suppose that is because it was not in as big of a server, thank you so much that worked
Big servers lead to more events, if you have all intents you're using much more resources than what you really need
also For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.
question do i replace bot.load_extension('command.afk') with await load_extensions("afk)
?
It should be await bot.load_extension
they're probably not using discord.py
intents = discord.Intents(messages=True)
bot = commands.Bot(command_prefix='-', intents=intents)
I am using this to declare intents, and the intents are given on the developer portal too, but it still can't access message.content
I get this in the console on startup
message content not messages
also don't use discord.Intents(...) that doesn't enable any of the other non-privileged intents
use discord.Intents.default() instead
I need someone who can create custom bots. Im starting an agency that creates, manages discord servers and creates custom bots
Then you can get developers on websites such as Fiverr, not here
Nah I need one person who is always available
wth
Then you're in the wrong place
try posting a job on upwork
how to make balance or economy feature with embed link? pls tell experts
hello i am expert
simply set up a database and fetch a value from it
how need codes
?
what are codes for that am new to learn python
my import discord and from discord.ext are coming in yellow line also
tried, failed now asking
nobody will give you it, you have to make it yourself
Pip install discord??
yep
import time
s = 1
while True:
time.sleep(s)
s = s**10**240
i want to learn python
noted
that escalated quickly
🔥
how to set up database
i tried using bridge commands but i get this error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums'
what discordpy version are you running?
Well, that
discord.py-2.2.3
ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums'
wym?
Whoops, didn't mean to edit the message
are you trying to import it yourself or it happens in the library source code
library source code
show full traceback
You sure? You can show the whole traceback
what is that
Why did you delete the traceback
what file is that
And I believe it's called hybrid in discord.py
i copypasted more than i needed to
its called core.py in discord.py
should i send it again?
What
there is no such file in discord.py source
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
🫠
discord/ext/commands/core.py lines 51 to 63
from ._types import _BaseCommand, CogT
from .cog import Cog
from .context import Context
from .converter import Greedy, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
from .parameters import Parameter, Signature
from discord.app_commands.commands import NUMPY_DOCSTRING_ARG_REGEX
if TYPE_CHECKING:
from typing_extensions import Concatenate, ParamSpec, Self
from ._types import BotT, Check, ContextT, Coro, CoroFunc, Error, Hook, UserCheck```
i dont see this in discord.py source try updating to newest version
i did it runs the newest version
I don't even think it's discord.py anymore
now theres a big question mark above my head 
i am
do pip show discord.py in terminal
can you do pip list and check if there are no modules named: py-cord nextcord disnake
my discord bot worked just fine until i tried using bridge commands
nextcord and disnake has their own namespace
There are no bridge commands in discord.py
you can still import them as discord
at least you can do with nextcord

That explains it
you have py-cord
pip uninstall py-cord
yes
it was pretty obvious from the start as discord.py does not use the name "slash command" anywhere in its code
ok specialist 
y tho?
discord/app_commands/commands.py line 144
VALID_SLASH_COMMAND_NAME = re.compile(r'^[-_\w' + THAI_COMBINING + DEVANAGARI_COMBINING + r']{1,32}$')```
i see slash command in discord.py source
They have conflicting module name
they both react when you try to import discord
Did you delete both py-cord and discord.py?
Hi
was looking for help , wondering if something like this exists
Can you reroute a discord bot to display the message as a desktop notifcation?
I cant find anything online about it
"the message" what message? DMs?
not message
i mean not dms
well i guess dms and server
I just want the message to display on my discord so i dont have to tab to discord to see it
when im on fullscreen
yes
is that setting in server settings @smoky sinew
no client settings
is there anyway to copy text from the notification to your clipboard
from what ive seen online its impossible through discord
also is there a way to increase the notification size
the message gets cut off
Hello I am paying a person for a python script ME DM
you're asking for a self-bot though
that's against discord's TOS and against this server's rules
wdym its not discord related
what operating system are you using
you want to listen to notifications and copy their texts?
its not something thats like crazy important just would be less tedious
from having to manually go into my dms/server
and yeah if its possible create a custom notifcation
cause the message gets cut off
@smoky sinew windows
i don't think there is any way to do that then
unless you're using a custom version of discord
wait why
is it possible with any notification?
also if its not, is there an option where i can resize the notification window because it gets cutoff
this is no longer related to discord bot
probably through an external library
atleast two or three
which libraries do you have in mind
which platform are you on
windows
if you want we can take this to dms since this is the discord bots channel and this topic isnt deriving around the discord.py lib i just dont wanna get warned or banned
sure thanks
File "C : \User\lxlll\Downloads\orko_bot\orko_bot\main.py", line 129
await ctx.send(f'{member.mention} is not currently time out.
syntaxerror: '(' was never closed``` is this your error?
yea
parantheses was not closed
basically means you did not add another ')' to the very end of the line and finish the string literal
why me
you have cool color
first time? :)
im sleepy i didnt see that
nah it's perfectly fine bro
wait explain what the error is if you mind
That doesn't look like the full traceback to me
yeah^
there should be a full error log you can copy and paste into a file here
it would look like this
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined
``` or
>>> def greet(someone):
... print('Hello, ' + someon)
...
>>> greet('Chad')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in greet
NameError: name 'someon' is not defined```
but from what i see, its an error to do with .send()
so let me read over your code
looks like you're fetching the wrong id
nothing at all, it seems okay
it might be channel_id
alright give me a second to read over it
The channel is probably not cached if I had to guess
thats what i was thinking
bc theres no other way this error would appear
even intellisense recognizes .send()
what i would recommend is try with a different channel id and see your problem
it isnt a permissions error bc you didnt send the full traceback to do with that specific line
Use fetch_channel if get is returning None
more effective solution, try his
it's practically like get_channel
except you await it and it fetches it directly off of the discord api instead of the cache
most of the time all channels get cached if your guilds intent is enabled
what intents did you pass to your client?
oh wait your issue never had anything to do with get_channel returning None, this partial traceback proves it didnt
discord's API returned some error code when you tried sending a message, for example 403 Forbidden when your bot doesnt have the necessary permissions in that channel
is that what it is? he never gave the full traceback log
so i was going off of what line it was
oh then yes, use administrator or the permission you require
well what other error would you expect from an http.send_message() method defined by the library?
Looking back I think they're right.
The full traceback still goes a long way though 
yeah they're right
you need to await it
for which API
if youre doing this in a discord bot use aiohttp, that way it wont stall your code
whats your code
any other commands registered under "ban"
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
"""Ban a member from the server"""
await member.ban(reason=reason)
await ctx.send(f'{member} has been banned from the server.')
dms
alr
Sus
how I can make my bot spam messages by command I tried for loop but when I use the command it show big error to me
iterate over how many times you would like to send a message continously with a for loop
and await ctx.send()
while loop , define how many times it should run the loop , have the await message sending method beneath it , everything else should be outside the loop
okay
or better for , if you want the code to be more optimized
``import discord
from discord.ext import commands
import os
import requests
import string
import random
bot = discord.ext.commands.Bot("a")
@bot.command()
async def start():
channel = bot.get_channel(1115921187164409918)
for i in range(15):
channel.send("Im working")
@bot.event
async def on_ready():
print("online")
my_secret = os.environ['Token']
bot. run(my_secret)``
wouldnt recommend because rate limit
with start() you're missing mandatory parameters and await
defining the rate of loop iteration to fit the rate limit*
I will set await and try
But what is start
might you post the error you getting? , await is missing *
async def start():
youre missing ctx in the function
that too
no no
basically, in the command you are missing a mandatory paramater
its start(ctx):
swearing is not against the rules
oh is it not?
no
fine then
as long as it's not a slur
You also need to enable intents
^
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
yeah no fine
This dude better post the error he's getting , to get the full idea of what he's facing
The Unban in async def should be small capped
You can't use capital letters for command name
And can u show the error traceback
Is this the whole traceback??
Who are you trying to unban??
It is unable to find any guy with the user id that you are trying to unban from your server
What?
I don't see anything in the traceback that is implying that
Is this acc banned in the server?
There are 2 errors in the trace back
Yeah second one is related to your connection
Oh right
Ofc bad
U can try creating a new terminal but as far as i can tell first one is that you are trying to unban someone whose id is not accessible to the bot and second is the connection
Still the same error the bot is unable to detect the user id
Do you have members intent?
Enabled in dev portal?
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
Use that instead
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
my bot got verified :D

Congratulations, was it the first one?
yup
It took them 2 months for them to verify my first bot and second got things done within an hour
it took a morning
because they emailed me for some extra stuff
discord support is also like this 🤡
Their support is significantly faster than it used to be
still useless
@thin raft what's your bot btw
It's a music bot that plays music from a single artist
it was meant as the server bot but people wanted to invite it
so it ended up verified lol
do you know python?
that's not how objects work, you need to get a guild object such as interaction.guild
await interaction.guild.unban(...)
and make sure the command is guild_only and locked to the proper permissions
which it isn't here
To disable all slash commands in dms I typically do
for commands in self.slash_commands:
command.body.dm_permission = False
Is there fr no other nice solution for that (disnake)
man these days I've been learning about networking with twisted and it is interesting ngl
what
does disnake not have app_commands.guild_only
and GuildInteractionContext or something
!d discord
still no
why does it change every day
!d python
@app_commands.guild_only()
@app_commands.checks.bot_has_permissions(ban_members=True)
@app_commands.checks.has_permissions(ban_members=True)
But I wondered if there are any constructor kwargs or methods to disable them without that (I couldn't find any)
makes it so your command can't be used in dms
Yes
Do you recommend "Automate the boring stuff with python" to a beginner like me to learn at least the basics?
does anyone have a app_commands.group example
ask in #python-discussion
groupcog or group?
Is it in bot's dms
I don't understand how tihs works
can I declare commands inside of it?
There's a literal example below isn't there
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
Yes
literally shows how to declare it
I think it works just as a normal cog
that's not how that works
you can't ban anyone
you're not in a server it's impossible to ban anyone in dms
no that's groupcog
wait what
I remember one dude had code like this
for user in ctx.guild:
await ctx.author.ban()
The command was supposed to ban a single member 💀
It practically does
it will work but it will ban the member a few hundred times lol
Since when is Guild iterable
I forgor
u forgor the 💀
that's what checks are for
Make bot private and that's it
it's a verified bot..
Checks then
probably because you used has_any_role
the channel isnt yours man
still, it's better to explicitly state @app_commands.guild_only()

