#discord-bots
1 messages · Page 824 of 1
this should work fine, are you sure youve saved it and whatnot?
Similar to how loading cogs works, is it possible to use a for loop that will add fields to a help command?
I may have just found my way to automate help command
Tried restarting the bot and it worked fine, thanks for suggesting it
well message.content.lower() should work fine
is there some code you could show? also try debugging it; try printing message.content to make sure it triggers, the codes updated, etc
Nope, it just had to restart i think it works now
that works if you have a small bot with a few amount of commands, but sometimes its better to just use text in a description or smthing because you can only have a couple fields
From a cog, how could you find the class name of another cog?
cog.qualified_name
!d discord.ext.commands.Cog.qualified_name
property qualified_name: str```
Returns the cog’s specified name, not the class name.
Returns the cog’s specified name, not the class name
realised it said this, but ill assume that you're not setting a specific name
Instead of the filename - because my filenames are different to class names - I want the class name
Type e.g Misc / Admin
this works for class name assuming you havent done anything fancy
which i dont think you have
give it a shot
How would I use cog.qualified_name in the code I just sent?
ah
no, don't use this method
okay
you only want to use that for loading cogs
to get all the cogs the bot has do bot.cogs
!d discord.ext.commands.Bot.cogs
property cogs: Mapping[str, discord.ext.commands.cog.Cog]```
A read-only mapping of cog name to cog.
i already have cogs loaded
i know
I tried using this before and it seems closer to what I want to do
When I try to implement walk_commands() it says it is not defined
.
Not really no
i wont teach it right now
you need to learn it
list comprehension is quintessential to your python
Could I have any links in order to learn list comprehension?
ill link something and explain it as well
nothing to really learn. you just should know when its best to use it
>>> squares = []
>>> for i in range(10):
... squares.append(i * i)
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
goes to
>>> squares = [i * i for i in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
from realpython
you can do ```py
for cog in bot.cogs:
cog is an str of the cogs name
to get the cog instance its bot.cogs[cog]
eg to get the commands in a cog it would be:
for command in bot.cogs[cog].walk_commands():
print(command.name)
# you can add this to a list (lests call it cog_commands) because you dont know list comprehension
# add this to the embed
embed.add_field(
name=cog,
value=cog_commands```
list comprehension is a one line list
so to get all the commands in a cog it would be [cmd.name for cmd in cog.walk_commands()]
!list
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if statement:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
Both your examples remind me of this from when I have seen it before just that it is not known to me as list comprehension
ok
def generate_integer_list() -> List[int]:
"""
Generates a random list of integers
Returns
-------
List[int]
A list of integers generated randomly
"""
int_list = [randint(0, 100) for _ in range(randint(2, 10))]
int_list.sort()
return int_list
this is an example of a function i made that generates a random list of integers with elements that can be in between 0 and 100, and there can be at least 2 elements and at most 10 elements. its made with list comp
seems pretty pointless
so would it be something like for cog in but how would you get all cogs in a ./cogs folder?
you dont need to get all the cogs in a folder
you just do bot.cogs and it gives you all the cogs your bot has
sort of
cog returns the str name of the cog
so that would probably be in name
and to get the commands you would do [command.name for commands in self.client.cogs[cog]]
bearing in mind you need the command name not object
hence the .name
this seems like a lot to take in
something ... happened?
noo
you need to loop through
and do it in the value
you still want to loop through the cogs
think about it logically
cog is not defined
yes
[command.name for command in self.client.cogs]```
what would be this equivalent in a long list version?
that may make more sense to me as to what is going on
to get the cog name you can iterate through all the cogs the bot has py for cog in self.client.cogs
now you have the name of the cog (cog), you need the commands, correct? so to get the commands you would use cog.walk_commands() where cog is the instance of cog. To get the cog we will do self.client.cogs[cog] which returns the cog instance (self.client.cogs returns a dict with the name being the key, and the cog instance being the value).
to get the commands in the cog it is [command.name for command in self.client.cogs[cog].walk_commands()]
so then it would be ```py
for cog in self.client.cogs:
cog is the name
cog_commands = [command.name for command in self.client.cogs[cog].walk_commands()]
cog_commands is a list of all the commands the cog has
all you have to do now is add the name (cog) and the commands (cog_commands) to the field
wdym
im butchering this explanation
ah ok
no point appending a list to a list
instead you want to join the list
value = ", ".join(cog_commands)
you want to join the list so its a string not a list
!join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
thanks
This is starting to give errors?
It is due to help.py
this runs successfully
have you accidentally imported some weird ass module
ive never seen that error and i assume you havent done any _closing
myEmbed.set_author(name= ctx.user.name)
await context.message.channel.send(embed=myEmbed)
user = ctx.message.author
it says ctx is not defined
whats context and whats ctx
huh
context is the funtion and u said ctx is the person who used the command
ctx stands for context
oh
you've tried to add a command to a help command
can you show your code
you havent passed ctx
ok
#Imports
from discord.ext import commands
import discord
import json
import os
#Setup
with open ("token.json") as jsonFile:
jsonObject = json.load(jsonFile)
jsonFile.close()
TOKEN = jsonObject["TOKEN"]
INTENTS = discord.Intents.default()
client = commands.Bot(
command_prefix = "!",
intents= INTENTS,
case_insensitive = False,
owner_id = 828768915370278972
)
client.remove_command("help")
#Load + Unload
@client.command()
async def load(extension):
client.load_extension(f"cogs.{extension}")
@client.command()
async def unload(extension):
client.unload_extension(f"cogs.{extension}")
#Run
for filename in os.listdir('./cogs'):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
client.run(TOKEN)
My main file (client.py)
on of the field values is empty, meaning a cog might not have any commands
yes i have an event cog
you can do if cog == "event": continue meaning it would skip that loop iteration
ye
context.author.name - also I recommend renaming context to ctx - just kinda naming conventions. Also, for set_author(name = context) its context.author.name.
ps you can just do await context.send(embed=myEmbed) and remove the message.channel part
remove client = discord.Client()
ok
you have redefined it to commands.Bot
yea
pip install discord.py
This shows the same error?
well whats the cog event called?
also you dont need the else
didnt work
it says requirements met
already satisfied
that means you have multiple python versions installed
try and figure out which one you use, and uninstall the resrt
Sorry, it is late midnight where I am and I appear to be loosing brain cells
its often python and python3
Hi, anyone who's good with Disnake, I need help.
My bot won't load cogs, even though I've used bot.load_extensions().
It also doesn't throw a traceback error when loading the bot
how do you do 2 inputs and separate them? so like (command) mcc! bossman fjay but separate bossman and fjay and keep them by themselves
most of us here use disnake
Ah ok
where i can find all of them
im gonna need a bit more info than this
idk, ask in #python-discussion
I'll get my files one sec
if anyone knows @ me in reply
#main.py
import disnake
from disnake.ext import commands
import os
from decouple import config
token = config('token')
bot = commands.Bot()
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}.")
bot.run(token)
#ping.py
#this is in the folder "commands"
import disnake
from disnake.ext import commands
class Ping(commands.Cog):
"""Pings the bot to see if it can reply to commands correctly."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send("Pong!")
def setup(bot):
bot.add_cog(Ping(bot))
you would just do ```py
@bot.command
async def command(ctx, bossman, fjay):
you now have bossman and fjay values```
can you show me how youy're loading your extensions?
is there a way with discord.py when the bot tries to send a message with more than 2000 characters or more that it sends it automatically in 2 or more messages?
thats not how im doing commands im doing them like if msg.startswith("mcc! "):
you would have to subclass context and bot and it gets a bit complicated
so is it possible to so it with msg.split
and also the input can be anything not specfically bossman and fjay
this is not recommended in the slightest, but you can do args = msg.split() and then you have the bossman and fjay seperated
bot.load_extensions("commands")
.split() automatically splits by whitespace
where? xd
Why isn't it there-
lol
I don't know, one sec
#main.py
import disnake
from disnake.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
token = os.environ["token"]
bot = commands.Bot(test_guilds=[938194100639895713])
bot.load_extensions("commands")
@bot.event
async def on_ready():
print(f"{bot.user} is loading into developer mode...")
bot.run(token)
There
It copied my old one
is there a file in your directory called commands.py?
ah
its load_extension not load_extensions
I knew it existed, it worked, my bot files got wiped, it broke
so you have a directory called commands?
im not sure if its looking for an __init__.py
This finds the name but what about if i wanted the description of the command?
you would do command.name + command.description
ill take a look at the source code of load_extensions later and see how it works
@manic wing so i changed the code but i get this when i run it
you're running the bot multiple times
def load_extensions(self, path: str) -> None:
"""Loads all extensions in a directory.
Parameters
----------
path: :class:`str`
The path to search for extensions
"""
for extension in disnake.utils.search_directory(path):
self.load_extension(extension)
There
yea i need to save it
it might be trying to load __pycache__
i think load_extension might be better `
this has no check
you can do ```py
import os
for cog in os.listdir('commands'):
if not cog.startswith('_'):
bot.load_extension('commands.' + cog[:-3])
give this a go
newest version for python is 3.10?
windows python is a fuckery
true
so thats the reason its happening?
well ... yeah
Gives the value as all cog_commands in that cog but most of my cogs have only 1 command so how could I make the name have the command and value have command description?
but when i try it without running it again i get the same output
because you're running it multiple times...
reset bot token
ok
fk man it didnt work
oh name = cog + self.client.cogs[cog].description
registered? why would it get registered
its not a slash command
well uh
Ima take that as a yes.
@commands.command()
async def ping(self, ctx):
await ctx.send("Pong!")
``` this is a command
not a slash command
do you know how to make a slash command?
still giving requirements already satisfied
familiarize yourself with that directory
this makes a command
so that should work fine
Woo!
nice!
I got it working, thanks Caeden :))
it still only gives the name of the cog?
no problem, one down, infinite more to go
I'm sure of it.
have you set a description inside the cog?
Calling it now, I'll be back in 10 minutes for a dumb as fuck reason.
you set a cog description like ```py
class cog(commands.Cog):
""" this is the description """
we've all been at this stage before
not a problem
Mine doesn't have that.
I have one set, but no description pops up
do you want the command description or the cog description?
so you need to set the cog description
this is setting a command description
import disnake
from disnake.ext import commands
class Ping(commands.Cog):
"""Pings the bot to see if it can reply to commands correctly."""
Mine doesn't have a description even though there's one set
how?
this is how you set a cog description
using """"""
I have?
yes, its called a docstring
im talking to AVC
O
lol i thought it was used to comment out extremely long lines of code
no, docstrings are used to provide information - you're thinking of commenting
no, thats not what docstrings are for
ever thought how they programmed a programming language?
Just in this instance, it's used as a docstring
Some mad wacky 1s and 0s probably
def func() -> str:
"""
Returns
-------
str
"""
return "hi"
``` this is a docstring
binary
no
same is a programming language
computers can't read things like what we write
binary is the lowest form of computer interpreted language, then machine language which is base level shit just under c/c++ - python was made in c or c++, i cant remember
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Computers read programming languages after converting to binary
yes, but its not the same as the source code we write. it is machine code that it reads
for cog in self.client.cogs:
if cog == "Ready":
continue
cog_commands = [command.name for command in self.client.cogs[cog].walk_commands()]
helpEmbed.add_field(
name = cog + self.client.cogs[cog].description,
value = ", ".join(cog_commands),
inline = False
)```
Not exactly what I was looking for
well make it look nice
this is my help command
have you got any scholarships or degrees in Computer Science?
thousands, my name is Linux Torvalds
I used a docstring to put in a description for the command and it doesn't show said description on the command
BRO YOU'RE ON GOOGLE

you did it incorrectly then didnt you 
How come? It looks the same as how you put it?
import disnake
from disnake.ext import commands
class Ping(commands.Cog):
"""Pings the bot to see if it can reply to commands correctly."""
thats a cog description, not a command description
O
you guys are getting docstrings for cogs and commands mixed up
take a second to slow down and think about the logic
Lmao
It's 10pm, thinking of logic isn't possible rn lmao
Where would I put the description for the command then?
as i said, slow down and think about the logic
its straight forward...inside the command
description=“”
im making them use docstrings instead
Ohhhh
to confuse them less and to educate
should i delete those
class cog(commands.Cog):
""" this is the cog description """
@commands.command()
async def command(ctx):
""" this is the command description """
foudn them here
whacking out random shit probably isnt the best idea
Lmfao
go to settings>uninstall
still getting requirements already satisfied issue
uninstall other python versions
dont fuck around with the files themselves or you'll piss off the application
application will wonder where the fuck its files have gone and it will throw a tantrum
Just delete This PC
i was gonna suggest that
Great minds think alike
remake your pc
there is just those
switch to linux
well looks like you only have one python version
ye
either switch to linux or create a help channel, i dont fuck around with windows enough to help you fix microsofts problems
alright
Microsoft rly pain in the ass all the time
if you want you can just sue microsoft and see if they give you some cash to afford linux
linux is free
not all of your cogs have descriptions it seems
@manic wing do u have an idea in which channel they can help me
ty
I have the help cog in which the help command is in, ping cog which does have a description, and ready cog which is ignored?
You cant have no value for value kwarg
Does Help itself need a description?
yes
Fixed it
yipee
Nice
Now for the aesthetics
good luck.
lol yes
Just steal the design
for cog in self.client.cogs:
if cog == "Ready":
continue
cog_commands = [command.name for command in self.client.cogs[cog].walk_commands()]
helpEmbed.add_field(
name = cog,
value = self.client.cogs[cog].description,
inline = False
)
await ctx.send(embed = helpEmbed)```
Can I delete cog_commands since it is not in use?
if you want
it might be useful later
Comment it out and see if anything breaks
If It’ s not used u can get rid of it
Mby ur ide alr shows if It’ s being used
VS Code has this thing where stuff not used turns a darker shade i.e cog_commands is a darker blue than other variables
Then yea u can delete it or comment it out if you will need it later
any way to make this automatic instead of listing all cogs incase I have too many later on?
Is Ready a name of a cog?
class
Idk what you are tryna do
With this
someone knows a way to go a new line without using "\n"?
Enter 🤷🏼♂️
funny
well i don't know if it works for a bot message
it goes through all cogs and if it is named "Ready" it will ignore because ready only contains events not commands therefore cannot be used in help embed. how can i make it so it will instead ignore all cogs that only contain events?
Id just use \n honestly except if u got a good reason not to
I think it does, not sure
?
what
this requires manual typing. is there a way to check if a cog has a command, if not then ignore it, else add to help
found another way
Nice
declare a variable and put my string in it
well uh
you can undelete cog_commands
i still have it
and do if not cog_commands: continue
and remove this
so then cog_commands will have to be defined before it instead
you just add this check before the embed add field
ye
@pine crypt https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=help#discord.ext.commands.HelpCommand I believe It’ s this class that you can inherit and make ur own help command
don’t recommend subclassing to a beginner 😢
AVC dont follow this i beg
Are these valid functions of ctx?
Should beginners be making bots tho
I made a bot 2 years ago and it failed badly
U should probably learn oop first
Do yk oop
yes thats good
Nope
My parents do automation testing in python
They know oop?
U should learn oop
can i somehow hide role specific commands from 'help' command?
Or google “how to be pro oop-er”
Inherit HelpCommand
what?
Do yk oop?
what's that?
Object oriented programming
Learn it, It’ s important
No need to be
ok so how can i hide a command from the help command?
Discord has a set character limit but an embed doesn't count as actual text so would an embed be worth 1 character?
I think there is a character limit within embeds
what
theres a different between content and embed
Base model rewrite looking good so far
you can have 10 embeds in a message and 2000 characters
10 embeds per message max
oh 10
what model rewrite
All model
whats the model for
I'm rewriting all the models I have in the wrapper
The model is just a skeleton class for discord models
Making it easier to add them
andy can you have 10 images and 10 embeds on a file
I don't think there is a limit on files
Amount wise*, so as long as its under 8 MiB
It would be fine to send
damn im thinking of how to send the largest message now
lots of \ns in the content and embeds, and as many white files as you can fit in
Just put a dot, then a lot of new lines and then another fot
Dot*
There's a limit of 10 attachments at once
@manic wing
At least there is for normal users, idk about bots
Ah, ok that makes sense
Although I don't really see an obvious spot in the docs that say this limit
Lol I'm not done with my help command yet
Time to add buttons and pages
Bruh this is gonna take a while
How to add buttons?
How to add pages?
similar to this?
Cya
Hello! mee6 how did you solve that embed doesn't have a name just value?
translate is shit
so, how can i make embed similiar MEE6? Mee6 dont use names, use only value.
\u200b
o ty
you get the emoji id
await (await client.fetch_user(466829347953836033).send('I joined '+guild.name))```
anyone know what I'm doing wrong it's saying it was both never awaited and it's a nil value
<:emoji_name:id> to get the id you can put \ in front of the emote you post in chat
what the fuck is this cursed code
I'm just trying to get the bot to dm me when it joins a server
someone else gave me that code but it didn't work
put it in seperate variables, that looks ungodly
to do it properly you'd have to mess with it even more
user = await client.fetch_user(...)
await user.send(...)
Looks much cleaner and would also fix your issue
oh alr will try that
Sometimes when you sacrifice readability and cleanliness you get errors that could've been avoided, so it's always best to keep your code neat and organized so that doesn't happen
Hey! How to get the object of a user in the server (with a given ID)?
I tried guild.get_member(id)
And bot.get_user(id)
Both return None
A member object?
Yes
The member isn't in the bots cache or its the wrong id
Guess it isnt in the bots cache then, but what about guild.get_member() then?
Same issue
get tries to get it from the bots cache
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
!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/master/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
I did
user = guild.fetch_member(id)
await user.remove_roles(role)
Says that this does not have that attribute
You have to await fetch
Oh I see lol
Yes, all fetch_* methods are asynchronous considering they make an API request. This is true of most coroutines in discord.py, if it's asynchronous then it's a good bet that it's making an API call. Because of this, it's preferable to stay away from making a direct API call when you can get it from the cache or some other source, since API requests can be slow
also you need member intents
there is
not for fetch_member(), member intents is required for getting member data from gateway
utils.maybe_coroutine is a coro
there are lots of coroutines that do non-api stuff
actually yeah there's a bunch nvm
discord/channel.py lines 201 to 202
async def _get_channel(self):
return self```
what?
because abc.Messageable.send() uses await self._get_channel()
Ok that makes a lot more sense now
it needs to be asynchronous because User.send() exists
hm interesting, Member._get_channel() is its own thing
oh ic, because User._get_channel() isn't copied over
Wonder why it isn't copied over though, the API treats Member as a wrapper for User with extra information, and even has a user field inside of the raw data given
the Member class is decorated with a method that assigns various properties, for example, Member.id is a getter, for Member._user.id
so i'm not sure what you mean
oh the method isn't copied over because its name starts with _ and the decorator ignores properties that do
You could probably make Member a child class of User
discord/member.py line 158
def flatten_user(cls):```
Saves some overhead
no, that's worse for memory efficiency
creating a full user object per guild member is kind of pointless
because a single user can be in multiple guilds, hence having multiple instances of Member associated with them
discord/member.py line 289
self._user: User = state.store_user(data['user'])```
yes
So, there would be a user for every member either way
But yea I do see your other point
no, _user represents a single instance of User
it's not like a User is created every time a Member is created
How can i make a comma dand send message bot who write the commad only seen it
it's simply a reference, that's all
hiiiiiii
Ah I see ok, but either way if you think about it though, if you created a User then cached it, it would overwrite the previous cache then later the garbage collector would free the memory for the extra user class
But yea I see now it's more preformant to not subclass it
i don't see what you mean, only a single instance of User is cached per user the bot can see anyways
bruh your mom is ugly
trying to make my bot send a message as soon as it gets a message from a specific channel ``` if message.content.startswith('$start_logs'):
if message.channel.find('Bot-Commands'):
channel = client.get_channel(941323760215138324)
await channel.send('s7')
member._user is simply a reference to that same user
I was talking theoretically for the case Member subclasses User
still doesn't sound correct
screenshots nft pfp
what is that meant to do?
why not use a command and check the channel?
when i type $start_logs in the bot commands channel, the bot says s7
How so, if you created a new User class when one exists already, then you cached that, you'd just be getting rid of the old created class, if there is no reference to it the garbage collector will free the memory allocated for it
if message.channel.find('Bot-Commands'):
this is confusion
idk im new to python and i thot that would work ;-;
without that it works if i type start logs in any channel
thought* what you spelled is a bad word lol
Hey no bullism
well then why create multiple instances? that's just not great either for performance
Again 
im not its just not a good thing to say lol
self._user = state.store_user(data['user'])
this line basically creates a user object if it doesn't exist in cache, caches it, and then returns it
if a cached user exists, it returns that instead, and ignores the data passed to it
i changed it to ```@client.event
async def on_message(message):
if message.channel.startswith('logs'):
if message.content.startswith('$start_log'):
channel = client.get_channel(941323760215138324)
await channel.send('s7')
it still didnt work
it said the startswith altribute is wrong doesnt work
google tf
help?
it says it
ik, that new chapta from google, how to solv it in my bot
it says to many request
too many request to the sorry/index E
isnt that bcuz bot havent solve the chapta?
ok, so i just need to wait or what
you got ratelimited by the api
an 429 means the client has done too many requests
The bot be like let me in
ok then
btw hullo
hi
youll have to wait
you can check the apis docs to see the ratelimit
so something like this doesnt happend again
i ned help
With?
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
wont work?
show
show code?
yes
you arent replying to anything it should be
await ctx.reply()
since the Context class has a reply method
!indents
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
😔
if you cant fix indention errors you shouldnt be coding a discord bot.
why so sad :((
Spitting fax
ik how
You're about to yell at me for my implementation of the user object
😔
it better be good😡
You'll be disappointed

I haven't even started
🧍♂️
what do i put for it all to reply
also why do you call the set_footer() function twice? while the first one has the text kwarg with no value passed.
everything you want it to reply with
okay
tyik
Context.reply() works so much like Context.send(). difference being that it will do a reply to the Context.message which is the message you use to invoke the command.
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
sorry abt tha
the thing that bothers me most is that they used "client" as their bot object variable.
nah its fine but you should follow it
same lol
discord.Client() exists, so does the bot object. name your discord.Client() object "client", and the bot object "bot". not the other way around.
I have a question maybe someone could help. Im pulling some data from an api and passing it to a variable called totalminted. Then im trying to display that variable in a embed message but I get the variable name instead of what the variable is storing. Im sure im just pluging it in incorrrectly but Im not sure how to make it display the varaiable data.
@client.command()
async def cher(ctx):
embed = discord.Embed(
title = 'Lorem Ipsum',
description = "Lorem .",
colour = discord.Colour.orange()
)
embed.add_field(name='Total Nfts Minted', value='totalminted', inline=False)```
'totalminted' is that really a variable though 
Remove the '' or use {totalminted}
Ok that is what I though. Im converting to a string right?
Correct
Thank you!!
does the cooldown decorator work for application commands too?
how do i make it so it mentions the person "godlent"
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
Can you center a string inside an embed so its center aligned?
is anyone willing to prtner with me to build a discord bot? (Coded in Python of course) Dm me if your interested
try embed1, not 1embed lol
ik but did that
didn’t work i took button out shut wont work
I have code that replies, hold up, lemme find it rq :)
the thing you are looking for is
await ctx.reply(codehere)
opponent = random.choice(Characters)```
It's saying "set object is not subscriptable" in errors what does that mean
Characters is a table of strings only
well characters is a set which you cant do such an action on it
oh wait I accidentally used a { instead of a [ mb
lol
how do i see which platform a user is on?
thanks baby
Don't think you can
you can only check if a member is on mobile,
!d discord.Member.is_on_mobile
is_on_mobile()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): A helper function that determines if a member is active on a mobile device.
def drop_card():
picture = random.choice(os.listdir("cards/"))
#file = discord.File("cards/" + picture, filename=picture)
embed = discord.Embed(color=discord.Color.blurple())
embed.set_footer(text="Do $claim <> to claim it!")
embed.set_image(url="attachment://" + picture)
return embed
``` the image doesn't get attached
embed.add_field(name='Utility', value="afk , userinfo , serverinfo , invites , av , join , leavevc , disconnect", inline=True)
```are these utility commands fine? or i add another category
ok
ok
means
anyone i have a weird red line that says its not closed
Don't hardcode a help command
means??
It means don't hardcode a help command?
hardcode?
🚪 🏃♂️
@final iron i understand now lol
how can i get the commands?///
!d discord.ext.commands.Bot.commands
property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Commands' object has no attribute 'me'
newly added cogs
what
..
I wanna wait for 2 possible texts from a user, (yes or no). I was thinking of using wait_for but I have no idea how I would do something if they say "yes" and do something else if they say "no"
error
just check message.content and whether it equals something
for example:
message = await client.wait_for('message')
if message.content == 'yes':
...
elif message.content == 'no':
...
this example is very basic and very prone to bad user input btw
then show your code, we don't read minds around here
Alright yeah got it, that wait_for will wait for any message from any user though right? So I'll check the message author too in the if
Just use a check
yeah but I have 2 different conditions
do something if yes, do something else if no
i didn't understand how I would implement checks with that
def check(msg):
return msg.content in ("yes","no") and msg.author == user
```
Its slightly wrong but i hope u get it
msg author should be msg.author
class Commands(commands.Cog):
"""huh?."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.guild_only()
@commands.command(name="kick")
# @commands.has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member=None, * , reason=None):
if ctx.me.guild_permissions.kick_members is not True:
s = discord.Embed(description="I dont have kick perms",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
elif user is None:
s = discord.Embed(title="Define the member",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
elif ctx.author.top_role <= user.top_role:
s = discord.Embed(description=f"{user} | Is Mod/Admin cannot kick",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
elif user.top_role >= ctx.me.top_role or user.guild_permissions.administrator:
s = discord.Embed(description="The user has bigger role than me cannot kick",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
else:
lol = discord.Embed(title=f"You are Kicked from {ctx.message.guild.name}", description=f"**Reason**: {reason}", color=aqua,timestamp=datetime.utcnow())
await user.send(embed=lol)
await user.kick(reason=reason)
kick = discord.Embed(title=f"Kicked {user}", description=f"**Reason**: {reason}", color=green,timestamp=datetime.utcnow())
kick.set_footer(text=f"Requested by {ctx.author}", icon_url=f"{ctx.author.avatar_url}")
await ctx.reply(embed=kick)
def setup(bot: commands.Bot):
bot.add_cog(Commands(bot))
yeah I get it but again,
.
let me give an example, say I'm selling all my items.
I want the bot to send a confirmation message. If I reply with yes, it will sell it, or else it won't sell it. Now I just don't know how to integrate it with checks because if the check fails it doesn't even raise an error I think
the check should just return a truthy or falsey value.
usually the check is put in place to make sure the channel and author are the same for both messages, any other logic is usually put after the message is received
i've seen a lot of people who've unfortunately forgotten about while loops and have a big ass chain of wait_for, or they just stop the back and forth exchange when the end user makes an error
This will keep listening to messages until you get either a yes or no message, why a while loop?
try:
msg = await wait_for()
except TimoutError:
return await send('timed out')
...
try:
msg = await wait_for()
except TimoutError:
return await send('timed out electric boogaloo')
# or
msg = await wait_for()
if condition(msg):
msg = await wait_for()
if condition(msg):
msg = await wait_for()
...
else:
return await send('try again')
else:
return await send('try again')
avoid this
while loop for back and forth stuff
you missed the self parameter
first parameter has to be self, ctx and other parameters follow after that.
how do i know what permissions does the user need on a missingpermissions error
!d discord.ext.commands.MissingPermissions.missing_permissions
The required permissions that are missing.
thanks
cool
def drop_card():
picture = random.choice(os.listdir("cards/"))
file = discord.File("cards/" + picture, filename=picture)
embed = discord.Embed(color=discord.Color.blurple())
embed.set_footer(text="Do $claim <> to claim it!")
embed.set_image(url="attachment://" + picture)
return embed #i send it using await send(embed=drop_card())
``` image doesn't get attached
no bro youre uncool
!d send
No documentation found for the requested symbol.
file=file
lol
!d discord.abc.Messageable.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
use file =
oh
no
lol i always forget its .abc.Messageable
that sends a file
Do you send the image file?
doesn't seems so
so what u want
no? i don't wanna send the file
i just wanna send the embed with the file as it's image
then?
he wants to attach a img in a embed
await ctx.send(embed=embedname)
How do you suppose it to get added in the embed then?
yes
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
Read this.
thats what i did mate
ok
last part?
No wtf
lol
Read the full message.
ctx.send(embed=embedname)
Or atleast the first linem
see he has used it
thats what i did
??
no
great
i did it earlier, the file got sent by itself and not inside the emebd
Why do you expect random.choice to be same for both the command /event which you use to send the choice and the drop_card function
i don't use random.choice in the event
i only use it inside the function
ok
and how do you send the file then?
await message.channel.send(file=file, embed=embed) the output is the ss i sent earlier
🤨
!d embed
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
how is file defined in that function?
file, embed = drop_card()
But you returned only embed
😵💫
that was the new function
i returned the file and embed in the old one
nvm guys i'm using disnake again because it has a file kwarg in set_image sorry for wasting your time
lol
bot.voice_clients
bot is not defined i just shifted to cogs
class Commands(commands.Cog):
"""huh2?."""
def __init__(self, bot: commands.Bot):
self.bot = bot
```in the class
self.bot
^
huh?
your class has a bot attr use it
self.bot
self.
no
somhow i cant use it
self.bot.voice_clients
not working
i need a team to make a movie streaming website
how is that not working
capital S?
no idea
no
btw ```py
voice = discord.utils.get(self.bot.voice_clients, guild=ctx.guild)
thats the problem lol
enough of python let's talk about pyutin
if its not defined its not in the class
ctrl -
Zoom out
innit press control and minus
how?/
I use the mouse scroll+key combination
ok
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
So only the code, and not the complete ui gets zoomed out
@nimble plume
self isn't defined
hec
yes
@slate swan
…
yes
..
did you my dude write all of that but don't know how to add self argument
yes
i think
🤨
…
oh congrats
😅
🎉
silly mistake
that's what i literally said though
Also do pep8 a favour and leave a line between methods
So it looks nicer
okk
na effort
hope you didn't mess up ur code
okk
LMFAOOO
😅
How to remove all the components from a message in disnake? Thought about editing it with empty view but is this correct
u can remove_item too
.edit(view=None)
i have a hex code inside a string, how do i make it hexadecimal so that i can pass it to the embed colour
Use int with base 16
No?
then how
!e print(int("10", 16))
that's definately not what I did
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
16
!e print(int("ffffff",16))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
16777215
oh
How does the string you're getting look
Ah
just strip. # from that
Strip off the hashtag symbol and use int as demonstrated
👍
is it possible to send messages every day at a specific time in my timezone
!d discord.ext.tasks.loop
discord.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://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
no i dont mean like that
Use this with 1 second loop
and you can compare your timezone's time using datetime module
i tried that but i cant calculate it properly so can i do 4:00pm or something like that
!e import datetime
print(str(datetime.datetime.now()))
Lmao
Compare it with this format
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2022-02-14 08:08:56.566757
how do i change pm and am with this 💀
0-12 is am, 12-23 is pm
so i could do this every 5 minutes and check if the result is what i want it to be
but wait i'll have to change 2022-02-14 every day
you can just use the time part of that
yeah but if i do wont the 2022-month-day be included
I am making music functionality to my bot and there is a problem with the play commands. Everytime i play a song the youtube_dl works perfectly the bot join the voice channel but an error named FFmpegPCMAudio has no attribute _proccess
Here is the code
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Hey @brittle axle!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
wait this is about ffmpeg
not youtube_dl
I cant ask about that too?
or nvm
that also break rule 5
Bot can connect to the call, but it won't send the chat and won't play the audio. What should I do?
else:
if x < 2.5:
word = random.randint(1,2)
if message.author.bot:
return
if word == 1:
await message.author.voice.channel.connect()
await message.send("test1")
await message.guild.voice_client.play(discord.FFmpegPCMAudio("example_01.mp3"))
await message.guild.voice_client.disconnect()
if word == 2:
await message.author.voice.channel.connect()
await message.send("test2")
await message.guild.voice_client.play(discord.FFmpegPCMAudio("example_02.mp3"))
await message.guild.voice_client.disconnect()
lol
help
im getting error
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 608, in _load_from_module_spec
del sys.modules[key]
KeyError: 'utility'
bot.load_extension("utility")
Seems like the bot can't find a file with name utility
what does ctx.voice_client return ?
does it return member vc or bot vc ?
does
ctx.voice_client
same as
guild.voice_client and member.guild.voice_client
It returns an instance of discord.VoiceClient for that guild
hello guys, how can i make command "only you can see this"
ephemeral responses which can be generated only through interactions
Hey guys, im trying to host my bot on Pebblehost and im getting this
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.verfication' raised an error: ImportError: cannot import name 'NoneType' from 'types' (/usr/lib/python3.9/types.py)
the error isn't present on my main PC
and ive also imported "types
msg.content.count("\n") or smth ig
how to enable pyenv shell on manjaro?
If somebody can code bot what will download every picture what is send it would help me
How do I check if the bot is in the same voice channel as the ctx.author ?
anyone know the solution to my issue?
wym
can somebody code discord bots in python
!d discord.Message.attachments
A list of attachments given to a message.
!d discord.Attachment
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") and is hashable.
but can it download
yes it can
oh ok
!d discord.Attachment.save
await save(fp, *, seek_begin=True, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this attachment into a file-like object.
what he said ^
