import discord
from discord.ext import commands
import os
from apikeys import *
bot = commands.Bot(command_prefix= '!',intents=discord.Intents.all())
intents = discord.Intents.default()
intents.members = True
@bot.event
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
initial_extensions = []
bot.run((BOTTOKEN))
#discord-bots
1 messages · Page 259 of 1
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def aide(self, ctx):
help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
help.add_field(name="Modération :", value="!ban | !kick", inline=False)
help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
help.set_footer(text="Demandé par : {}".format(ctx.author.display_name))
await ctx.send(embed=help)
@commands.command()
async def music(self, ctx):
await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")
@commands.Cog.listener()
async def on_member_join(member):
channel = bot.get_channel(1121386561150386276)
join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
join.set_image(url=member.avatar.url)
join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
await channel.send(embed=join)
def setup(client):
client.add_cog(Greetings(client))```
There is no load event
So your load function wasn't called at all.
create a listener for on_ready and run your load function in that
import discord
from discord import Client
from discord.ext import commands
bot = commands.Bot(command_prefix='-')
#ping command
@bot.command()
async def ping(ctx):
latency = round(bot.latency * 1000)
await ctx.send(f'Pong! Latency: {latency}ms')
print('hello world')
bot.run('token')```
The bot is not responding to commands.
you need to do intents
!intents
Using intents in discord.py
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.
raceback (most recent call last):
File "c:\Users\Mikey\OneDrive\Desktop\FreelanceFinderBot.py", line 8, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'
seems like you're not on the latest dpy version
how does one update it?
it still say me that my command is not found ```python
import discord
from discord.ext import commands
import os
from apikeys import *
bot = commands.Bot(command_prefix= '!',intents=discord.Intents.all())
intents = discord.Intents.default()
intents.members = True
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
initial_extensions = []
bot.run((BOTTOKEN))
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def aide(self, ctx):
help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
help.add_field(name="Modération :", value="!ban | !kick", inline=False)
help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
help.set_footer(text="Demandé par : {}".format(ctx.author.display_name))
await ctx.send(embed=help)
@commands.command()
async def music(self, ctx):
await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")
@commands.Cog.listener()
async def on_member_join(member):
channel = bot.get_channel(1121386561150386276)
join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
join.set_image(url=member.avatar.url)
join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
await channel.send(embed=join)
def setup(client):
client.add_cog(Greetings(client))```
you put the function inside of the event, you didn't call it.
where do i need to call it
move the function outside of the event, and run it in the event.
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'c:\python310\lib\site-packages\pip-22.0.4.dist-info\entry_points.txt'
Consider using the --user option or check the permissions.
do
python --version
just so i can see the python version
I am very outdated, have not coded with discord py in ages. ~
3.10.4
can you show me how u ran the install command
like this ? ```python
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
load()
pip install discord.py
yes but you need to await it
and fix your indentation for your load function
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
await load()
indeed, perfect
and if you want to do a like 'successful' load message for each cog, you should add an event listener inside of the cog its self (the "on_ready" event) and print it that way, just person preference
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 28, in on_ready
await load()
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 19, in load
await bot.load_extension(f"cogs.{cog_name}")
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Greetings' raised an error: TypeError: object NoneType can't be used in 'await' expression```
my issue has been fixed
show me your cog "greetings"
ah wait i see the problem, you need to make the setup function async
in your cog*
Import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def aide(self, ctx):
help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
help.add_field(name="Modération :", value="!ban | !kick", inline=False)
help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
help.set_footer(text="Demandé par : {}".format(ctx.author.display_name))
await ctx.send(embed=help)
@commands.command()
async def music(self, ctx):
await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")
@commands.Cog.listener()
async def on_member_join(member):
channel = bot.get_channel(1121386561150386276)
join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
join.set_image(url=member.avatar.url)
join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
await channel.send(embed=join)
@commands.Cog.listener()
async def on_member_remove(member):
channel = bot.get_channel(1121386771087904828)
leave = discord.Embed(title="Un membre a quitté le serveur !", url=None, description=f"Oh non aurevoir {member} :wave:", color=0x7434EB)
leave.set_image(url=member.avatar.url)
leave.set_footer(text=f"Nous sommes désormais : ")
await channel.send(embed=leave)
def setup(bot):
bot.add_cog(Greetings(bot))```
you need to make your setup function async
how ?
huh wdym how, make it async lmao, just like how you made your 'load' function async
the init ?
def setup(bot):
bot.add_cog(Greetings(bot))
```this function of your cog, needs to be async.
oh ok
i need to await ?
ah wait the setup function doesn't need to be async i was wrong, sorry
i think no bc it print me
YEA IT WORKED TYSM
but i still have a question
lets hear it
why do i have an error in my listener
pass 'self' to the function and do self.bot.get_channel i believe it is, im not 100% sure but i assume thats it, if not i can check and tell you
yes i think it worked
ty
Anyone know how to fix this
[2023-06-27 22:35:46] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
[2023-06-27 22:35:46] [INFO ] discord.client: logging in using static token
[2023-06-27 22:35:47] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 4fc3408fa438cb372ad247f8db170185).
can anyone help me fix this
my bot spams t
!intents
Using intents in discord.py
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.
thats fine.
may someone please help me with this error https://pastebin.com/z4yFivAX
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
can you please show me the json data you are trying to load?
ok
help me pls #1123408368493678802
It's better to prove error with source code so people can understand it better and help you
Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/cogs/Moderationcmds.py", line 67, in mute
await ctx.guild.mute(member)
AttributeError: 'Guild' object has no attribute 'mute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'mute'
i am not
also could of said it nicer but guess not thats how people are these days.
await member.timeout()
Those doesn't work with guild
this exact error has been fixed for you like an hour and a half ago...
no offense, but are you basically not reading?
#1123398244941176832 message
this is a message i sent befour
and i am not cause i know javascript
Then use djs
trying to learn something new
Learn python first
the hell u think i am trying to do for god sake
Jumping into dpy library
adding laugh emojis very funny hahaha not fuckin funny
Triggered
print(f(bot.user.name) "is online"
i did something wrong guys
The error is the (f at the start
So you're trying to format a string?
!f-string
Format-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
And also you didn't close print with )
@wispy locust ?
yes?
!rule 10
Working fine for me
not for me
what is gonna happen?
What did you choose
Choose bot in SCOPES
Then PERMISSIONS according to your preferences
@warped mauve
.
Look if you have genuine question you could ask. this channel isn't for fun or chill don't waste other's time here
r u a undercover moderator?
i just wana know
dont ban me
bot > admin
just those 2
@warped mauve this is imp
Here you can choose anything you want
And you'll get your url
that’s what i did
Make sure your bot is public
no luck
They don't generate links for private applications
it is public
One more way
https://discord.com/api/oauth2/authorize?client_id=??&permissions=8&scope=bot
i fixed it
Put your bot id at ??
make sure its public
Well good
It requires 2 factor code whenever someone tries to add bot to server
If it's off i can add bot directly to server
If it's on it requires my 2fa code to add it to server
async def mute(self, ctx, member: discord.Member, *, reason = None):
guild = ctx.guild
permissions = discord.Permissions(permissions = 0, read_message_history = True, view_channel = True, send_messages = False)
if await guild.fetch_roles("Muted") == True:
mute_role = await guild.fetch_roles("Muted")
else:
mute_role = await guild.create_role(name = "Muted", permissions = permissions)
await member.add_roles(mute_role)
await ctx.send("Muted the user!")
What's the issue?
Error occured: Command raised an exception: TypeError: Guild.fetch_roles() takes 1 positional argument but 2 were given
Why not fetch role using id
You can store id in database
guild id : mute role id
1 mute role per guild
More efficient
hm im just a beginner rn
Okay lemme look at documentation real quick
alr
@hasty pike fixed it. So fetch_roles returns a list of all the roles of the guild
thats why my code wasnt working
anyways thx
That's what i figured out
You can try ```py
"if is in"
does discord have areas where you can host discord bots ? (online 24/7)
miss type
Hosting on you, discord doesn't provide any
i see
Show code
have u downloaded discord module
oh yeah show the code
commands.Bot()
from discord.ext import commands
I don’t wanna look stupid if it’s a dumb code
There's no commands module in discord
isnt that invalid?
Figure it out
it is
Don't worry everyone messes up sometimes i had done same mistakes as this when i was leaning
Can u look at DMs
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="/", help_command=None, discord.Intents.all())``` u can use this
I fixed the old error but im stuck in another mess xd
Then what is support channel for?
@woven schooner
Invalid syntax
!e
def a(b, c):
pass
a(c=0, 0)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 4
002 | a(c=0, 0)
003 | ^
004 | SyntaxError: positional argument follows keyword argument
U want me to use that?
ye
intents = discord.Intents.all()
oh yeah, forget to pointed that out
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="/", help_command=None, intents = discord.Intents.all())
async def on_ready():
print("logged in")``` u can use this
Show your code we'll point out where you went wrong and solution to it
async def mute(self, ctx, member: discord.Member, *, reason = None):
guild = ctx.guild
permissions = discord.Permissions(permissions = 0, read_message_history = True, view_channel = True, send_messages = False)
guild_roles = await guild.fetch_roles()
if "Muted" in guild_roles:
mute_role = 'Muted'
else:
mute_role = await guild.create_role(name = "Muted", permissions = permissions)
await member.add_roles(mute_role)
await ctx.send(guild_roles)
``` i was trying to do this but the bot is creating new even tho there is already one
Indentation
Indention error
guild_roles = await guild.fetch_roles() if "Muted" in guild_roles:
F
guild.fetch_roles returns discord.Role objects
I got all this stuff off the py cord website this what it said to do
And you can't compare them with strings
Ew
oh well
It’s all probably messed up
You leaked your token
Idc I’ll reset it
My our token you mean?
(and that's not how you should be using environment variables)
from discord.ext import commands - (line 2)
bot = commands.Bot() - (line 7)
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
Exactly 
@woven schooner reset token and check usage of env variables
guys
i put the bot token in a folder and i wonder how i can get stuff in the file thats in the folder
You just need to reset token that's it
ill show pic wait
No big deal
Idk which bot it was
I created like 20 doing this thing trying to get it to work

print(f'{bot.user.name}')
It'll show you bot's name
You don't need 20
Ik I was getting new ones cause I thought it’s was the bot that was wrong
What line
Put it inside on_ready
async def on_ready:
print(bot.user.name)
well this wont work?```py
discord.Role(name = "Muted")
Invalid syntax
You already have
Stop pointing out I won't write detailed 10-20 line codes here
as you can see the token is in the folder, but i want to access whats inside that file so i can use it in the main file
oh then?
@woven schooner run it and you'll get bot name in result then reset for that name
What's wrong with pointing errors out
have u learn py basics?
I get this
i havent learnt py basics but ive watched tutorials
You can use the from token import bot_token
- I hope you have TOKEN = 'token' variable
it does but TOKEN is not in caps
You can't import Python files if it has spaces in its name tho
how do I access the role name from the list returned by fetch_roles, kinda confused
What do I do
You can just sort it by checking the role.name attr
Cause I get this
With list comprehension and similar things
commands.Bot(command_prefix="!", intents=discord.Intents.all())
This is mandatory
You can name anything
Just use same where you need
Is it supposed to be like this
i have a TOKEN var in the bot_token file
alright
bot_token.TOKEN
did that
wait lemme try
anyways, calling a file bot_token ain't really it
call it
bot_config.py
(function) TOKEN : Any
@swift edge lemme grab you ss from my bot you'll understand

any1?
I just answered it, or you want to access the role's name?
role's name
Then just role.name
oh
Why does no one use pydantic for loading bot settings 😔
What is it?
whats that
Data validation using Python type hints
What is it's use?
It's pretty neat
Also underrated
Primarily for data validation but it has a feature of easily managing settings (like bot tokens)
@unkempt canyon uses it as well
.env works
It works but is not nice to work with IMO
I still keep getting the has no attribute to ‘bot’
Too lazy to read documentations 😂 i need tutorials
Show code
same xd
Make sure you saved changes
Show error
ima just watch a tutorial
inside discord.Role or what
Still don't get it?
What do you mean inside
It's an attribute of the discord.Role object
i do, but ill watch a tut so i can learn how to access something properly
The name of the role.
What library are you using
Wym
oh sry
The Discord API library, like discord.py, disnake and stuff
Did you import discord library properly
It’s just pip install discord is it not
Okayy
No
pip install discord.py
Says I already have
Hmmmm
Do pip freeze
You could have multiple libraries with the same module name
@commands.command()
async def mute(self, ctx, member: discord.Member, *, reason = None):
guild = ctx.guild
permissions = discord.Permissions(permissions = 0, read_message_history = True, view_channel = True, send_messages = False)
guild_roles = await guild.fetch_roles()
if discord.Role.name("Muted") in guild_roles:
mute_role = discord.Role.name("Muted")
else:
mute_role = await guild.create_role(name = "Muted", permissions = permissions)
await member.add_roles(mute_role)
await ctx.send(guild_roles)```
What will it say
It will tell what packages you have installed
It says I have a bunch of stuff that I don’t remember downloading
Happens 😂
Is that bad
Probably because they're dependencies of some libraries
Cause all I’m trynna do it just to get it online and I’ll be happy
Can you show the screenshot of it
I still cant get the variable in a file thats in a folder
You have both py-cord and discord.py, you should uninstall one of them
Which ones better
(discord.py)
What's the problem
from folder.file import variable
folder = folder name
file = file name
Ok I deleted py cord
Now it should be working fine
lowkey
High key
just download the github repo and put it in the same folder
When I run it I still get the same thing can one of u send like the code to turn it online and see if that helps
take this
doesnt work
Error occured: Command raised an exception: TypeError: 'member_descriptor' object is not callable
ima try rephrasing my problem
show ss
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
bot.run(TOKEN)
in this ss, im trying to get a variable in a file thats in the token folder, the file name that im trying to get the var in is bot_config
The bots token is located in the bot_config file, im trying to put that token in the parentheses after bot.run at line 10.
from token.bot_config import token_variable
from token.bot_config import TOKEN
It’s saying the same thing I thing something’s wrong
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
Use replit.com easy solution for you
If your code doesn't work, replit wouldn't magically make it work
It's cloud based IDE so local packages won't trouble
Saying what
we can use this in most of the cases in dpy?
The bot thing
.
Are you sure it's the same thing?
aint no way
import discord
from discord.ext import commands
client = commands.Client(command_prefix="!", intents=discord.Intents.all())
client.run(TOKEN)
@woven schooner run this
There's no commands.Client
It works
Where are you getting these things
I already have it up
so it says on my requiremnts.txt discord==2.3.1 and im running py3 couls that be the issue? why my import discord doesnt work?
Experiments a lot of experiments 😂
My main bot use client
Because you don't have it installed?
i have it installed for py2.3.1 ig what is the pip for new one?
What
There are no such thing as discord.ext.commands.Client
There's only discord.Client
How about we just give him a bot subclass?
but always get errors its not installed
My pc is going in the trash rn
It’s goin right in the trash can
It’s saying the same stuff
idk

discord.utils.get() what attribute is used to search if a particular role from the mentioned user
Just try to run it on replit.com
It's no big deal
How do I run on this
Oh nvm
It’s a big green button
For some reason it always says this to like
And idk what that even is this is my first time using Python
Yk what that is ?
Is says it on py too
It's from discord.py's source code
Always read errors bottom up
The stuff at the bottom of traceback is the most important and the most relevant to your code
Can u delete all of the sources code
No because discordpy needs that to work
py3 -m pip install --upgrade discord.py==2.3.1
'py3' is not recognized as an internal or external command,
operable program or batch file.
my goal is to unistall discord and isntall the one for py 3.11
or whatver idk
brain hurty
Is there a way to completely reset all of my Python like it deletes everything
Files and all
.
why??
did you first configure the interpreter used by your IDE
Cause I always get errors from stuff I never did
Like line 788 I don’t have that many lines
reinstalling python is not going to fix your error
no idk what that means im new to py
I did that but it didn’t help
go enable the intents in dev portal
you are using vscode, yes?
no?
then which IDE?
https://chat.openai.com/share/6bbf11ea-8519-4379-8ef7-67d15a07e621 go to discord python bot part and go to the end .-.😤
and this is IDLE for Py 3.11.4?
it shows the full version when you open it
3.11.4 yes
im not getting the error when using IDLE im using a 3rd party thing for hosting but im getting that error so i assume its my PC
Man this hard
OI
then that looks like an issue with your hosting service
what do you need help with
just read the chatgpt share link
the whole problem in in the the conversation between me and chat gpt
yo how to fetch all the roles of a particular user
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
MMMMMMMMMMM
in this ss, im trying to get a variable in a file thats in the token folder, the file name that im trying to get the var in is bot_config
The bots token is located in the bot_config file, im trying to put that token in the parentheses after bot.run at line 10.
go to https://discord.com/developers/applications setelect ur application click bot then reset token then copy token then delete TOKEN replace it with the text that you copied from your application bot
intents.messages is not intents.message_content
wot
can i use it with discord.utils.get?
@swift edge
you are wrong
oh
you are wrong
@bot.event
async def on_message(message):
if message.content == bot.user.mention:
await message.channel.send(f"My prefix here is `{bot.command_prefix}`. Try `{bot.command_prefix}help` for more info!")
why does my bot stops responding when I runthe code with this event added
message_content not messages_content
I swear you cannot read
My guy
please go learn some python
**intents.**messag__e_content__
ty
Sometimes people not even knowing the most basic Python is more than annoying
💀
they don't even try
OMG TY
i started using python 2 days ago
print(discord.Member.roles)
No print user roles ;(
discord.py/bots are not made for people who started learning python 2 days ago
ok teach me
learn it from docs or yt
where
I learnt from yt
i will dox u
Docs, books, courses, school, etc.
it worked
Surprising
fyi, client mods like you have can lead in your account getting terminated 
what im using better discord 💀
And it's against the terms of services of Discord
its not illegal
oh i dint know
but almost 800k ppl use better discord
It's website which provides cloud editor to write and run codes it's good for testing your code
Then almost 800k people have the possibility to get terminated
Lots of people doing something doesn't make it allowed out of nowhere
and discord knows about this and does nothing
just like minecraft launchers
Again, my point is that it's against ToS
ok
downloading discord then going into files and changing rgb and and stuff is illegal?
ToS are not laws
So no it's not illegal, you won't go to court for that
Doing such client modifications can get your account terminated though, yes.
so that means i cant hack my self nitro xd
hi i have an issue when the commands is sending two times ```python
import discord
from discord.ext import commands
import os
from apikeys import *
bot = commands.Bot(command_prefix= '!',intents=discord.Intents.all())
intents = discord.Intents.default()
intents.members = True
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
await load()
initial_extensions = []
bot.run((BOTTOKEN))
you're probably running the same file twice
exit them both
?
close whatever you're using to run the python file and restart it
nvm
k
i didn't work
when you stop the program from running, does your bot still reply?
quick question: how to host the bot
no
how are you running the bot?
and what are you testing to see if it replies twice?
with vsc and i type a command called "!aide"
in one of my cogs
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def aide(self, ctx):
help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
help.add_field(name="Modération :", value="!ban | !kick", inline=False)
help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
help.set_footer(text="Demandé par : {}".format(ctx.author.display_name))
await ctx.send(embed=help)
@commands.command()
async def music(self, ctx):
await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")
@commands.Cog.listener()
async def on_member_join(self, member):
channel = self.bot.get_channel(1121386561150386276)
join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
join.set_image(url=member.avatar.url)
join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
await channel.send(embed=join)
async def setup(bot):
await bot.add_cog(Greetings(bot))```
strange
I'd say, either close all python programs in task manager first before running again,
or basically just restart your pc
because there are somehow 2 processes of your bot running
(and they somehow stop running both once you stop one)
Bro you're getting on rules since morning
m
btw, a bot constructor has an activity, status kwarg please use those instead of change_presence in the on_ready event
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
=>
bot = commands.Bot(..., status = ...., activity = ...)
also, please use a setup_hook to load your cogs
as on_ready isn't the place to do so
It's your choice if you don't follow rules you'll face consequences for
even when i have restarted my pc it runs twice ... idk
can't be, it does any command twice?
where can i do it ?
I explained it all
oh ok
normally no
but does it now?
add a test command and rerun your bot, check if that responds twice too
yes
since i move everything in cogs
in a cog or in the main
load your cogs in a setup hook
the ones mentioned in web are free vps or paid
Wherever you like
and?
?
that's good...
bruhhh
Setup hook should be used inside bot subclass if I'm not wrong
They're paid
not necessarily, but it's suggested, yes
but not much like $5-10 a month
Ohhh
to accept file as arg do you just typhint discord.File?
I'd think so, yes
you can always try
.Attachment iirc ( atleast for slash cmds)
yeah, might be that instead
in then main it respond normally
well, as mentioned earlier
last 2 lines
but in a cog it respond twice
https://discordpy.readthedocs.io/en/latest/migrating.html#command-extension-changes
this is how you want to load your cogs:
by extending your bot class & overwriting the setup_hook
in there, load the cogs
mind the # after using setup_hook in the second codeblock
you can choose any of those methods in the docs to load your cogs
just don't do it in on_ready

So i create a class in my main that loaded the cogs
you extend your bot class
@buoyant crescent on_ready executes when your bot is logged and online
But you need to load cogs before logging into a bot so setup_hook is for that purpose
so instead of bot = commands.Bot(...)
you'll be using that
class MyBot(commands.Bot):
... setup_hook(...):
# burp
# don't just copy, THINK too
await load()
bot = MyBot(...)
the main issue with on_ready is it having a probability of being called multiple times
hence it not being suitable for "startup tasks"
so I was thinking his cogs might be loaded in twice, but I'm not sure if that's even possible, as I would prevent cogs with the same name to be only loaded in once...

I've never had this personally (on_ready being called multiple times), so as a beginner, I was also using on_ready for these purposes
but now since setup_hook exists, I've been golden
def setup_hook(...): 
async
that's why I don't want him to copy
Sometimes You can make your own ways to do it instead of setup_hook 😉
The ... are probably more weird when self is one character longer
I did before that existed
Krypton is good entertainer here
learn to code it urself bro
@bot.command()
async def prefix(c):
await c.send("Prefix command1!!1!1!1")
No i know this
Intents
We don't spoon feed you, learn.
Is it possible to make lorem ipsum be indented too below the symbol?
You can use the \n for newline
!e
print("😳\nMeow")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 😳
002 | Meow
!intents you need to provide an intent value to your Client/Bot init
Using intents in discord.py
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.
But that's gonna make a weird formatting issue when the embed is seen from a phone, right? Like you'd have to calculate where exactly you should put a new line. Plus you'd have to put the indentation too after a new line.
not possible, since every user has control over their own zoom and you can't decide at what letter the line is gonna break

Okay, I suppose I'll just use a code block instead to separate them. thanks
Ohhhhh, right
IndentationError: expected an indented block after function definition on line 57
line 57: async def commands(ctx):
how to fix am noob lol
Indent correctly
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Among the first things you learn when using Python, if you'd actually learn it
you need to change the line as well
skull
commands. Bot (...)
these whitespaces 
bot = ( commands.
Bot(
command_prefix=".",
intents=(
intents
))
)

May I ask that is it possible to distribute slash commands codes to different files?
Wdym by distribute
Sure. Check out cogs.
Or if you want, you can do anything by yourself with add_command
Tch tch tch tch
commands.Bot inside () ??
Do you mean separate it to multiple files?
to make getting attribute on different line valid
Oh yes
didn't understand but okay if you say so
Cogs
How do you copy paste so fast
bot = commands.
Bot(
command_prefix=".",
intents=(
intents
))
will give an error
bot = (commands.
Bot(
command_prefix=".",
intents=(
intents
))
)
will not
ctrl + c, ctrl + v
Ohh does it really works this way?
Docs opened 24/7 in another tab xD
It's not very much time to open them
It's just "discordpy cogs" on google, click the link, ctrlc ctrlv
Is there a way to do that?
Ay eshaan what was the pip discord.py ?
pip install discord.py?
Yea is that the one I need for discord bots?
Yep
Ok
do i past python command_prefix= '!',intents=discord.Intents.all()
in this bot = MyBot(...)
Noo
Did you read docs
it says main
main what
Technically yeah but you would need to accept those args and pass to Bot constructor
# before
bot.load_extension('my_extension')
# after using setup_hook
class MyBot(commands.Bot):
async def setup_hook(self):
await self.load_extension('my_extension')
# after using async_with
async def main():
async with bot:
await bot.load_extension('my_extension')
await bot.start(TOKEN)
asyncio.run(main())```
Constructor missing
How do u install pip again
Shell command
Like when I download Python
how can i call the constructor
How do I get pip
where
# before
bot.load_extension('my_extension')
# after using setup_hook
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(command_prefix="!", intents=discord.Intents.all())
async def setup_hook(self):
await self.load_extension('my_extension')
bot = MyBot()
# after using async_with
async def main():
async with bot:
await bot.load_extension('my_extension')
await bot.start(TOKEN)
asyncio.run(main())
Not to you
Why to accept args and kwargs if you dont use them
Bad habit
Good practice
Installing python/pip is unrelated to this channel either way
Can create a post in #1035199133436354600
Well I was talking to
Doesn't matter
I was just askin him cause we was talking about it up there
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Rules are rules, follow them
@buoyant crescent
Ain’t gotta be a dick chill
How am i
Well installing modules or libraries aren't really my experties
No need to randomly insult for telling you to follow the rules
You can post #1035199133436354600 and someone will help you
.
Any issues with doing that?
how do i detect when a forum has been created?
how do i limit a command to only me
like if other try to invoke it, the bot should send some error msg
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
yes but how do i make it detect a forum?
im trying to make smthn that auto speaks into a forum when it is made
The channel will be of type discord.ForumChannel
oh so discord.on_guild_channel_create(channel) would be replaced with discord.on_guild_channel_create(discord.ForumChannel)?
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
Similar names: 2to3fixer.isinstance
im confused, sorry but can you give like 2-3 lines that would explain how to use it, im just a bit stuck
Google is your friend sometimes you know
Instead of checking if 5 is an integer, you check if channel is a discord.ForumChannel
discord.on_guild_channel_create(channel, discord.ForumChannel)?
yes
No.
im confused
Have you ever created an event
@commands.command()
async def test(self, ctx, member: discord.Member):
guild = ctx.guild
guild_roles = await guild.fetch_roles()
admin = discord.utils.get(guild_roles, name = "・Admin Bot")
await member.add_roles(admin)
Error occured: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
almost never used discord.py
Well your bot doesn't have sufficient permissions it looks like
You do not change how an event looks like, you use it
If the event is discord.on_guild_channel_create(channel) you don't add stuff, you use it as it is
So
@bot.event
async def on_guild_channel_create(channel)
it has admin
Admin doesn't bypass everything
so i do an if statement for if it is forum?
? admin perms?
Then I told you to use the isinstance() function, and not to add discord.ForumChannel to the arguments list
Is the top role of the member higher than or equal to the top role of the bot? Is the member the server owner?
Correct, it doesn't bypass everything
mb
if isinstance(channel, discord.ForumChannel):
So you end up with something like
@bot.event
async def on_guild_channel_create(channel):
if isinstance(channel, discord.ForumChannel):
# ...
If author executes help command and deletes command message then i want bot to delete response help message too?? Is there a way to do this
idk abt that but ik how to make the bot delete the response after certain time
if that would help u, then im glad to help
I know that but i want if I delete command bot should delete it's response too
i don't need this ? ```python
after using async_with
async def main():
async with bot:
await bot.load_extension('my_extension')
await bot.start(TOKEN)
asyncio.run(main()) ```
You do
!d nextcord.ext.commands.Bot.reload_extension
reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.Bot.unload_extension "nextcord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.Bot.load_extension "nextcord.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.
i'm a bit confuse, in my actual code what do i need to keep /delete ```python
import discord
from discord.ext import commands
import os
from apikeys import *
#bot = commands.Bot(command_prefix= '!',intents=discord.Intents.all())
class MyBot(commands.Bot):
async def setup_hook(self):
await load()
bot = MyBot()
intents = discord.Intents.default()
intents.members = True
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
await load()
@bot.command()
async def test(ctx):
await ctx.send("This is a text command")
initial_extensions = []
bot.run((BOTTOKEN))
Why would you ever need something like that to load extensions
why run load function twice
because my cogs are loading twice
in my code ?
because you made it to
yeah in which else
you are loading cogs in setup hook and on_ready event
If you run anything twice, it's going to be ran twice
Remove await load() from on_ready function
i add it after i got the bug
What bug
This code is giving me PTSD
my commands run twice
so loading cogs twice solved a bug you are saying?
no
i just didn't finish the setup_hook thing
Then just remove it from on_ready
You're messing things up yourself
ok
And where is constructor?
?
why you create intents when you dont use them
Where did you put command_prefix and intents
Don't bully him
How is that bullying
Intents are mandatory we know that 
just a simple question
bot = commands.Bot(command_prefix= '!',intents=discord.Intents.all())```
This code is so messed up even after he got alot help from channel
why you create custom bot class and still dont use it
To load extensions
Use this function and forget about bot sub class
so i don't use this anymore ```python
class MyBot(commands.Bot):
def init(self):
super().init(command_prefix= '!',intents=discord.Intents.all())
async def setup_hook(self):
await self.load_extension('my_extension')
bot = MyBot()
Either put this or use function above
since when did the super() init call occur
Both will work same way for you
it wasnt here
so is it ok now ```python
import discord
from discord.ext import commands
import os
from apikeys import *
class MyBot(commands.Bot):
def init(self):
super().init(command_prefix= '!',intents=discord.Intents.all())
async def setup_hook(self):
await self.load_extension('my_extension')
bot = MyBot()
intents = discord.Intents.default()
intents.members = True
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
@bot.command()
async def test(ctx):
await ctx.send("This is a text command")
initial_extensions = []
bot.run((BOTTOKEN))
He got all the help needed but still we didn't see any changes
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "c:\Users\MYOUSSEF\Desktop\bot\cogs\Music.py", line 13, in <module>
class Music(commands.Cog):
File "c:\Users\MYOUSSEF\Desktop\bot\cogs\Music.py", line 71, in Music
async def test(ctx):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1793, in decorator
return cls(func, name=name, **attrs)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 406, in __init__
self.callback = func
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 513, in callback
self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 130, in get_signature_parameters
raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)')
TypeError: Command signature requires at least 1 parameter(s)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 55, in <module>
bot.run((BOTTOKEN))
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Program Files (x86)\Python38-32\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 16, in setup_hook
await load()
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 30, in load
await bot.load_extension(f"cogs.{cog_name}")
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Music' raised an error: TypeError: Command signature requires at least 1 parameter(s)
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x03199C88>
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files (x86)\Python38-32\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
i got an error
yes ?
and then ctx
i put it
error says otherwise
whats the attribute for lock/unlock channel
exept the test command ;-;
File "c:\Users\MYOUSSEF\Desktop\bot\cogs\Music.py", line 13, in <module>
class Music(commands.Cog):
File "c:\Users\MYOUSSEF\Desktop\bot\cogs\Music.py", line 71, in Music
async def test(ctx):```
IT STILL RUN TWICE ;-;
using vsc?
what run twice
yes
show code
oh then prob because u lauched 2 times
import discord
from discord.ext import commands
from discord.ext.commands import MissingPermissions
from discord.ext.commands import has_permissions
from discord import Member
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
ban_words = ["ntm", "nike ta mère", "fdp","fils de pute","tg","ftg","Tg","Ftg","Fdp","Ntm","drakyne est gentil"]
for i in ban_words :
if message.content == i:
await message.delete()
await message.channel.send(":x: Tu n'as pas le droit de dire ce mot !")
await self.bot.process_commands(message)
@commands.command()
@has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member} a été kick')
@kick.error
async def kick_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":x: Tu n'as pas la permission de kick les membres")
@commands.command()
@has_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'{member} a été ban')
@ban.error
async def ban_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":x: Tu n'as pas la permission de ban les membres")
async def setup(bot):
await bot.add_cog(Moderation(bot))```
happened to me as well few days ago
i will try restart my pc
.
the command / event
.
maybe you are still loading cogs twice
import discord
from discord.ext import commands
import os
from apikeys import *
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix= '!',intents=discord.Intents.all())
async def setup_hook(self):
await load()
bot = MyBot()
intents = discord.Intents.default()
intents.members = True
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
@bot.command()
async def test(ctx):
await ctx.send("This is a text command")
initial_extensions = []
bot.run((BOTTOKEN))
print(f'Extension: {cog_name} succesfully loaded') does this print once per extension?
yes
Extension: Greetings succesfully loaded
Extension: Moderation succesfully loaded
Extension: Music succesfully loaded
2023-06-28 12:21:59 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 03db445d78a549032dbacde950a586ad).
The bot is now ready
--------------------
i already
send ss of terminal
ok
!d eval
eval(expression, globals=None, locals=None)```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.
I just want to create an app command with parameters that I can use to do other things in my function but I can't figure out how 💩 .
@client.tree.command(name="embed", description="embed a message")
@app_commands.describe(option="message to embed")
async def embed(interaction: discord.Interaction):
```
this is what I have started with
with the help of docs and stack overflow
you just add it as param to the function
the app_commands.describe is for giving them description
you will see in discord how it looks
ohhh okay ty
@slate swan tysm, the bot now has the parameters in the command but I am facing an issue with sending embeds. The text provided is what the bot says after I do the embed command which I will provide the code for below.
@client.tree.command(name="embed", description="embed a message")
async def embed(interaction: discord.Interaction, embed_title: str, embed_description: str):
embed_message = discord.Embed(title=embed_title, description=embed_description)
await interaction.response.send_message(embed_message)
tysm 🙏
it's a guess, check the docs
yeah im reading through the embed part rn
@spice dirge ur solution was right, didn't see anything meaningful in the docs but the bot can succesfuly embed stuff now
🙏
!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)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
I think that my braincells are not meaningful enough
I'm sorry
!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.
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
you can see what methods it has
Can i edit button response message twice in class?
Why not
How can i?
@nextcord.ui.button(label="Press me!", style=nextcord.ButtonStyle.red)
async def sayhi(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.edit_message(embed=discord.Embed(description='Updating...'), view=None)
await asyncio.sleep(1)
await interaction.followup.edit_message(embed=self.embed, view=self)
Save the message and .edit it twice
This is what I tried
Umm??
I don't think it will work, will it?
So you're saying
Try
msg = message
interaction.response.edit_msg()
Is this how you mean? @slate swan
Something about that yeah
Lemme try
@hasty pike i need your help lol
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix="!", intents=intents)
# COMMANDS
@bot.command(name="test", description="test command")
async def test(ctx):
await ctx.send("testing")
#START UP
@bot.event
async def on_ready():
print(f"bot is ready and logged on: {bot.user.name}")
from config import TOKEN
bot.run(TOKEN)```
the bot isn't responding
to !test command
Both intents = True
You're good to go
:o
its still not working
intents = discord.Intents.all()
Remove rest 2 intents
okay
@sharp whale command below on_ready
Discord Message Content Intent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
@sharp whale
Traceback (most recent call last):
File "/home/runner/papernodes-suggestion-bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 17, in test
view.add_item(button1)
TypeError: 'module' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/papernodes-suggestion-bot/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/papernodes-suggestion-bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/papernodes-suggestion-bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'module' object is not callable```
when i tried the button tutorial video you sent:
@hasty pike
It would be better if you show code instead of error
yeah sorry
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f"bot is ready and logged on: {bot.user.name}")
# COMMANDS
@bot.command(name="test", description="test command")
async def test(ctx):
button1= discord.ui.Button(label="Click me", style=discord.ButtonStyle.primary, emoji="⭐")
view = discord.ui.view()
view.add_item(button1)
await ctx.send("testing", view=view)
#START UP
from config import TOKEN
bot.run(TOKEN)```
!d
Hey, how can i change my discord token? Someone have it and he is griefing
No callback function
discord.ui.View()
V is capital here
Double check for capitals
Hey, how can i change my discord token? Someone have it and he is griefing
how to edit a message
Change your password
From the dev portal
There is nothing
Wich?
msg = ctx.send()
msg.edit()
Via id?
thanks
Which token you want to change?
ty
i should await the edit method ?
Yup
thanks again guys
Yes
What do you mean there is nothing?
There obviously should have something
!d nextcord.ext.tasks.loop
nextcord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://nextcord.readthedocs.io/en/latest/ext/tasks/index.html#nextcord.ext.tasks.Loop "nextcord.ext.tasks.Loop").
does a view class has a message or message id attr ?
No
!d discord.ui.View Why dont you check it yourself
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
thx
i run the bot it shows no problem but bot is not replying when I give him command
!resource
Is message content enabled? Do you have on_message event? Show your code
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
# Create a new bot instance
bot = commands.Bot(command_prefix='!', intents=intents)
# Event handler for bot startup
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
# Simple command example
@bot.command()
async def hello(ctx):
await ctx.send('Hello, world!')
# Command example: Ping
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
# Run the bot
bot.run(i wrote this')```
Message content is not enabled by default.
means?
Discord Message Content Intent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
Meaning this won't run.
so how it will run
Vitness provided the answer, read the embed and you should be able to get it running.
from here?
You don't need to remove something.
Look at the code, it's very similar to yours.
Here is an example of a basic bot -> https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
giving error
File "main.py", line 33, in <module>
bot.run('
')
File "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", line 860, in run
asyncio.run(runner())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", line 778, in start
await self.connect(reconnect=reconnect)
File "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", line 704, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
```
Re-read the embed, that answer is also there.
The error underneath also explicitly tells you to do something.
did you read it?
i cam't understand
"It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page."
what is so hard to understand in that error message
wait
English could be not be his native language.
google translate: 
What don't you understand?
😭
what is your native language?
Like just everything starting from Python? Or..?
hindi
You can use google translate yeah.
go https://discord.com/developers/applications/
enable intents
he can transtale that
what to tranlate
the error message ?
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
this?
yes this
bruh
फ़ाइल "main.py", पंक्ति 33, <मॉड्यूल> में
bot.run('
')
फ़ाइल "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", लाइन 860, रन में
asyncio.run(धावक())
फ़ाइल "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", लाइन 44, रन में
रिटर्न लूप.run_until_complete(मुख्य)
फ़ाइल "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", लाइन 649, run_until_complete में
वापसी भविष्य.परिणाम()
फ़ाइल "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", पंक्ति 849, रनर में
स्व.प्रारंभ की प्रतीक्षा करें (टोकन, पुन: कनेक्ट = पुनः कनेक्ट करें)
फ़ाइल "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", पंक्ति 778, प्रारंभ में
स्वयं का इंतजार करें। कनेक्ट करें (पुनः कनेक्ट करें = पुनः कनेक्ट करें)
फ़ाइल "/home/runner/cc-1/venv/lib/python3.10/site-packages/discord/client.py", लाइन 704, कनेक्ट में
किसी से भी विशेषाधिकार प्राप्त IntentsRequired (exc.shard_id) बढ़ाएं
discord.errors.PrivilegedIntentsRequired: Shard ID None उन विशेषाधिकार प्राप्त इरादों का अनुरोध कर रहा है जिन्हें डेवलपर पोर्टल में स्पष्ट रूप से सक्षम नहीं किया गया है। https://discord.com/developers/applications/ पर जाने और अपने एप्लिकेशन के पेज के भीतर विशेषाधिकार प्राप्त इरादों को स्पष्ट रूप से सक्षम करने की अनुशंसा की जाती है। यदि यह संभव नहीं है, तो इसके बजाय विशेषाधिकार प्राप्त इरादों को अक्षम करने पर विचार करें।```
i can't understand
not whole traceback just the error message
You only need the bottom part.
discord.errors.PrivilegedIntentsRequired: Shard ID None उन विशेषाधिकार प्राप्त इरादों का अनुरोध कर रहा है जिन्हें डेवलपर पोर्टल में स्पष्ट रूप से सक्षम नहीं किया गया है। https://discord.com/developers/applications/ पर जाने और अपने एप्लिकेशन के पेज के भीतर विशेषाधिकार प्राप्त इरादों को स्पष्ट रूप से सक्षम करने की अनुशंसा की जाती है। यदि यह संभव नहीं है, तो इसके बजाय विशेषाधिकार प्राप्त इरादों को अक्षम करने पर विचार करें।
``` this
so what to do
i copy code from here https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
just go and enable the intents in the dev portal man
read the message and do what it says
dev portal?
What it tells you to there, I reverted the text and it's still accurate.
open your bot's page and enable the intents you are using
Zeffo not having it lmao🗿
🗿
