#discord-bots
1 messages · Page 653 of 1
still nope
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
@bot.listen()
async def on_member_join(member):
role = member.guild.get_role(123456789)
await member.add_roles(role)
print("AUTOROLE TEST")```
DUDE
I have no words
LMFAOAOO
fancy a decorator inside a function
sorry sorry that was an accident
wait can you even put deco's inside a function
!e
def func(func):
func()
@func
def b():
@func
def a():
print(1)
return b
b()
display_name = for member in guild.members:
How do i do this
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
role = member.guild.get_role(123456789)
await member.add_roles(role)
print("AUTOROLE TEST")```
still doessnt work
eh
U gotta return the function
u dont use a for loop like that
o my bad
member_name = [str(member) for member in guild.members]
@boreal ravine :x: Your eval job has completed with return code 1.
001 | 1
002 | Traceback (most recent call last):
003 | File "<string>", line 5, in <module>
004 | File "<string>", line 2, in func
005 | File "<string>", line 9, in b
006 | NameError: name 'b' is not defined
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
role = member.guild.get_role(123456789)
await member.add_roles(role)
print("AUTOROLE TEST")```
That's a list comprehension
what why no work
command_prefix is supposed to be before intents kwarg i
Are you running the correct file?
you have two files
Main.py and autorole.py
Which file are you running
it runs both
No
what's member.guild.get_role()? everyone knows the real way to get a role is discord.utils.get(member.guild.roles, id=getattr(discord.Member, "guild").get_role().id)
what
member.guild returns a guild object, hence discord.Guild.get_role
yes
ok, but the method I use is superior
If the code is the in main file then yes
😤
Its not
You are still depending on cache
but why not just name, instead of id
so ur saying auto role.py wont work what so ever
helpful for people who get paid for every keyword written
you need to create .replit file
it is 😤😤😤
that tells what repl what field to run
how can 1x dumbass do that exactly?
wait, discord.utils.get is the same as get_ and not fetch_?
bruh
create a file called .replit?
then add this there
right
how are you that dumb though, just click the button??
his server is named xhaust, so it makes sense
nice
yes, discord.utils.get() is a method that gets objects based names and IDs through bot cache
so when i put this in a .replit file the autorole.py file will run?
yes
w h a t
is that not what u just said
my method is still superior
😤😤😤
nice
comes up with this and i cant run anything
cringe member.guild vs the chad getattr(member, "guild")
useless getattr func right there
nothing is installing or anything, it just doesnt run
This is not a channel to shitpost and flex
Please don't go off topic here
and to the fact, no one gives a shit how are you getting the Guild object
wrong chat
So no need flex because no one cares
This is not a channel to shitpost and flex. Please move to ot
Moving on
!ot
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
did you create the file?
it doesnt work
The big green button
yes
Wait do you have any code in autorole.py?
yeah
Show it
wdym?
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
role = member.guild.get_role(8932912395942)
await member.add_roles(role)
print("AUTOROLE TEST")```
That is in autorole.py?
yes
you need to run the bot smh
it doesnt workrkk
bot.run("token")
you didn't even add the run method at the end
ISTG IM SO SMART

good morning the command with what you send screenshot how it is what I have circled
When I send a photo I want the bot to send it as it is command?
yes
Then you need to read the attachment of the message and send it an embed use the
Embed.set_image() method
So
!d discord.Message.attachments
A list of attachments given to a message.
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
ok to ask something else on_message made an error
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\user\OneDrive\Υπολογιστής\Bots\main.py", line 112, in on_message
await message.channel.send(embed=emb)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\dpy_overrides.py", line 350, in send_override
return await send(channel, *args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\dpy_overrides.py", line 325, in send
data = await state.http.send_message(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
Code?
async def on_message(message):
channel = bot.get_channel('916945441696911371')
emb = discord.Embed(title=f"{message.content}", description=f"", timestamp=datetime.datetime.utcnow(),color=0xffffff)
emb.set_footer(text='Test', icon_url="https://cdn.discordapp.com/attachments/904787287857045504/916061762388914206/logo-advertising-image-marketing-brand-png-favpng-TRmTVi08NnDGxE9Pi3TsdhZbW.jpg%22")
emb.set_author(name=f"{message.author.name}",
icon_url=f"{message.author.avatar_url}")
await message.channel.send(embed=emb)
await message.delete()
First, this is bare message event is going to block your commands as it is overriding the default event
ok now?
second, it's trying to send a message to a channel where the bot cannot send the message
That's why its raising an missing access error
yes
spammy messages the boot
Yes it will spam
Because it's a message event
Every time someone sends a message the bot is also going to send the message
So yeah
wtf
So
yes
@bot.listen()
async def on_message(message):
if message author == bot.user:
return # this statement is important so that the bot doesn't respond to it's own messages
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
and you could create a command using the commands framework instead of use message events to make commands
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
async def on_message(message):
channel = bot.get_channel('916945441696911371')
emb = discord.Embed(title=f"{message.content}", description=f"", timestamp=datetime.datetime.utcnow(),color=0xffffff)
emb.set_footer(text='Test', icon_url="https://cdn.discordapp.com/attachments/904787287857045504/916061762388914206/logo-advertising-image-marketing-brand-png-favpng-TRmTVi08NnDGxE9Pi3TsdhZbW.jpg%22")
emb.set_author(name=f"{message.author.name}",
icon_url=f"{message.author.avatar_url}")
await message.channel.send(embed=emb)
await message.delete()```
this? @untold token
@untold token
whats da issue heer
it wont run
add the if statement that I said
code which you think is causing the error
from discord.ext import commands
import os
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
role = member.guild.get_role(8932970013213218975422295942)
await member.add_roles(role)
print("AUTOROLE TEST")```
🤔
@untold token 2 probs
bro why do you have your command_prefix like that
You aren't running the bot
its the same prefix defined twice in a list wtf?????
Lol
also its member: discord.Member not just member
its not running at all
dude did you listen to what i said, it's member: discord.Member not just member
That's just typehinting really
Will not affect the code
:troll:
O
🤔
forgot the :
@untold token know?
you are missing a .
doesnt run
message.author
You need to learn basic python
Hmm
Good
oh do i just copy the line and add main.py
i can run both right
@untold token the way ive done it doesnt work
how do i run both? im sorry for all this btw
such a pain
run="python3 autorole.py"
run="python3 main.py"```
You can't run both, create a single file and add all of your code in it
That won't work bruh
oh
ok
Make sure you only add the event
not other stuff
like the commands.Bot() and the imports
Works
ges
?
yes
Good job
tysm
Now learn basic python
will do
Because you did make me loose brain cells today
lmaooo
i feel accomplished
hi ! a
halp i got rate limited
its basically when discord receives too many requests i think
ohh
how can i fixx this now
u mean the events?
vents?
oh wait the commands
no like
@client.command()
async def foo(ctx):
await ctx.send("foo")
that function
or command ig
or event
just that one command
that which command
oki
data = await...
oh
im trying to implement my hangman game into my bot and i dont know how to read a user input through discord to act as the letter guessed
you need to use the wait_for method
message = await bot.wait_for("message", timeout=60)
message_content = message.content
thank you
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
how would i ctx.send() something the same way i would print(letters, end = "")
there is no end="" in ctx.send
wym
ik which is why im wondering how would i print the contents of a list in one line instead of multiple
!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'
thank you
The examples of wait_for
Ah hmm
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "c:\Users\user\Desktop\theBot\cogs\afk.py", line 111, in on_message
for id in self.afk.keys():
RuntimeError: dictionary changed size during iteration```how do i prevent his from happening?
for id in self.afk.keys():
await asyncio.sleep(1)
if message.author.id == id:
del self.afk[id]
embed = discord.Embed(
description=f"{self.bot.tick_emoji} Welcome back **{message.author.display_name}**! I have removed your afk.",
)
return await message.channel.send(f"{message.author.mention}", embed=embed)
```code (on_ready)
ignore self.bot.tick_emoji just some bot var
@commands.command(aliases=['afk'])
async def awayfromkeyboard(self, ctx, message="AFK"):
self.afk[ctx.author.id] = message
self.bot.afk_time = datetime.datetime.now().timestamp()
embed = discord.Embed(
description=f"{self.bot.tick_emoji} **{ctx.author.display_name}**'s AFK: {message}",
color=ctx.author.color
)
await ctx.reply(f"{ctx.author.mention}", embed=embed)```code (command)
thank you to everyone that helped me, my game is working as it should now
funny this is, i originally wrote the game in java for a homework assignment and then translated it into python
ah nice
I think the error means when the bot was trying to iterate through the dict (self.afk.keys) it changed sizes. I looked at https://stackoverflow.com/questions/11941817/how-to-avoid-runtimeerror-dictionary-changed-size-during-iteration-error and it says you can cast the dict self.afk.keys to a list to prevent this from happening but I'm not really sure lol
Holy mother of if statements:
if any(ctx.author.id in each_list for each_list in team1_ids.values()) is True and outcome in win_outcome or any(ctx.author.id in each_list for each_list in team2_ids.values()) is True and outcome in loss_outcome:
there's no need for the is True parts of that, since any() and in will return truthy or falsy (or in this case just True or False) values anyway
thanks, now what bout this? py Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 351, in _run_event await coro(*args, **kwargs) File "c:\Users\user\Desktop\theBot\cogs\afk.py", line 114, in on_message del self.afk[id] KeyError: 714731543309844561
what's truthy / falsey? is it like saying "truth-like / false-like"
yeah pretty much
for example "str" is truthy because it's a string with characters, whereas "" is falsy because its empty
Ohh change the name each time you mean? If that’s the case makes more sense
But am letting the bot give autorole to the member joins the server if that make sense hence why am using the client.get_guild
!keyerror
hm
well they key doesnt exist
try going afk first?
i think it happens when the user's afk is removed
hi can someone help me i have this problem how can i make it so that the names go into one embed this is my code ```py
@commands.has_permissions(ban_members=True)
@commands.command()
async def banlist(self,ctx,):
banlist = await ctx.guild.bans()
for ban in banlist:
user = ban.user.name + "#" + ban.user.discriminator
embed = discord.Embed(title = "Users Banned", description=user,color=0x910707)
await ctx.send(embed=embed)
append it to a list then use .join attribute on it
!e
banned_users = ["kayle", "night"]
print(", ".join(banned_users))
``` ^
who
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
kayle, night
ohh
that makes more sense thx so much : )
👍
just a little someone I know 😎
ah cool
Took me forever and a half to figure out
but I ended up going this route
user = queue[0]
queued = get(self.client.get_all_members(), id=user)
if queued != None:
await queued.send("Hello! Please prepare yourself, your trade it about to begin.")
indents are off from copy and paste but yeah
one thing when i do this i still get 2 embeds
but its not a list i dont think
you dont use join on a string
you use it on a list
check if the id is in there, if it isnt, use the return keyword
i dont think thats a good idea tbh
why ?
why not use add field
bad
i did
fields have a max limit
what
use the description
i did
you didnt
he is though
embed = discord.Embed(title = "Users Banned", description=user,color=0x910707)
^^
i mean for each banned user
in this for loop, if theres a banned user, it'll keep spamming those embeds
^^ move it outside the loop
yh
ohh ok let me try
^^
but if i do
i only get 1 person who is banned
that’s not a database?
no, you dont except if you only banned one person
iterate through ctx.guild.bans, append the users to the list, use join on the list
huh?
i did something new ```py
user = [ban.user.name + "#" + ban.user.discriminator for ban in banlist]
It's a language
just do ban, it returns the member object (kayle#999) and thats kinda useless
just append ban to a list
and join it somewhere
something like this~ ```py
ban = await ctx.guild.bans()
list = []
for user in ban:
list.append(user)
sql is a lang
sqlite, sqlite3, asqlite, etc is a database
SQL != sqlite
sql is structured query language
^
oh i thought both are same
sry mb
SQlite
if you wanna know if its a language, do this because discord can detect almost every language I think and if its highlighted that means its a language
And i think i solved it also that issue of yesterday
oh cool
imagine if i wud have replied "json" to that..
to this
I mean
no tbh
dogs is also a language
JSON is a database, but it isn't at the same time
tiget is also a language
What
cobra is also a language
it is a dictionary not a db
why u listing dead languages
used for config files
it is
ppl still use it
dead
zebra is also a language
every animal name is mostly a language
how do i get every message within a channel from specific user, i thought it would be this.. but didnt work
async for x in channel.history(limit=None, oldest_first=True, check=lambda e: x.author.id == 1290381039813209):
#etc
why are you listing every language 70% of people have never heard of
Julia
Is a lot similar to python
you have a lambda called e use it, you dont use x
and also author doesnt have an id attribute
i mean if C is a language then D must be to..
it doesnt take anything called check then
what is lambda?
wait what, it does, example using ctx, ctx.author.id
on a on_member_join event, doing member.guild returns the guild that the member joined.
!lambdda
its wavelength in sound terms
!lambda
..
Bruh
i know but it doesnt work like that
since x returns a discord.Message object, you could check for the member's id
an anonymous function
meaning?
whats the use of it?
dude
shorten your code
smh
nvm i got it
!d lambda
An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression
its smthn like pass
but used diffeerently
oof lemme dig into more
read this https://www.w3schools.com/python/python_lambda.asp <=
since x returns a discord.Message object, you could do something like```py
list = []
async for x in ...:
if x.author.id == ...:
#append the msg attribute you want to the list, then send the list ig
yes, not in embed titles tho mb
!d discord.Embed.url
The URL of the embed. This can be set during initialisation.
alr
cool thanks
👍
Yeah but it also returns the role when member joins
Wait am confused
Lol
Hai kayle 🙂
when recieving an embed, it has returned back 16685769 for its colour, is that hex or what?
If I want to get like API data from a json link every 5 minutes I use tasks right
yep
Yep idfk how to do that
hex contains letters too
code?
and output?
nevermind it returned the decimal value, i figured it out
@discord.ext.tasks.loop(minutes=5)
async def fetch_data():
#do stuff
#global the variable and do the required stuff
!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").
,-,
So if I like
@tasks.loop
Async def some_name(minutes=5.0)
bz = requests.get(url).json()
Is bz the global variable
7.12. The global statement
global_stmt ::= "global" identifier ("," identifier)*
``` The [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without `global`, although free variables may refer to globals without being declared global.
Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be used in the same code block textually preceding that `global` statement.
Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be defined as formal parameters, or as targets in [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statements or [`except`](https://docs.python.org/3/reference/compound_stmts.html#except) clauses, or in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) target list, [`class`](https://docs.python.org/3/reference/compound_stmts.html#class) definition, function definition, [`import`](https://docs.python.org/3/reference/simple_stmts.html#import) statement, or variable annotation.
!botvar or this is easier
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
oh I see
making vars global isnt recommended
botvars are better
no
this
Don't use globals...
!global will explain u why
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
Ok but which version is better
The bot version or just setting the variable when calling the function
just got done using alot of globals B)
yo
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
!d help fun
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
🙂
!d user ping
NumPy user guide
This guide is an overview and explains the important features; details are found in Command Reference...
Globals = no
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
is there a voicechat mute function?
servermute
!d discord.Member.edit I think this takes in a mute kwarg
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
the mute
Yea the mute kwarg, set it to True
ohh alright thanks
How do I remove the "answer to" with discord-py-slash-commands ?
wait no
slash commands use replies, there's no way to not do so
its for something else
its for permissions
wait nvm
my bad
fuck... because I must use slash commands to have a bot that still works after april 22nd 2022, but I don't want to have the replies
Welcome to 'discord thinks they know what devs want better than the devs'
and in DM's, it works without doing a reply...
Nice job discord 😭
it worked thanks
I want ping jog heart
?
I want discord user ping
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
Ah that
hi hunter and Caeden
if user is None:
create_level_account(ctx.author, ctx.guild, ctx.message)
data = get_data()
level = data[str(ctx.guild.id)]["users"][str(ctx.author.id)]["level"]
await ctx.send(f"You are level {level}")
elif not user is None:
create_level_account(ctx.author, ctx.guild, ctx.message)
data = get_data()
level = data[str(ctx.guild.id)]["users"][str(user.id)]["level"]
await ctx.send(f"You are level {level}")``` why is the `if` working but the `else` raises a key error?
its literally the same
!d discord.VoiceChannel.members
property members: List[Member]```
Returns all members that are currently inside this voice channel.
hi
elif not user is None?
doesn't make sense
i tried else aswell
it does make sense.
ye it does not after the if checks if that is NOT the case
!e py x = 1 if not x is None: print('...')
@manic wing :white_check_mark: Your eval job has completed with return code 0.
...
works fine.
it's funny how Python does not include grammar
!e py x = 1 if not x is not None: print('...')
@manic wing :warning: Your eval job has completed with return code 0.
[No output]
if you is not None:
should be
if you are not None:
Am I dumb? it's giving me a syntax error for some reason
seems like you indented it wrong
full ss 
or actually you put an extra bracket
funnily enough, you covered the line before which we need to see.
soo does anyone actually know 🤣
but yeah the indentation is wrong.
for image_id, link, name, owner in zip(image_ids, links, names, owners):
embeds.append(
disnake.Embed(
description=f"Displaying `{name}` by <@{owner}> (ID: {image_id})",
color=disnake.Color.blurple(),
).set_image(url=link)
await ctx.send(
embed=disnake.Embed(
title=f"{member}'s Profile",
description=f"Images: {image_ids}",
color=disnake.Color.blurple()
), view=EmbedPaginator(
ctx, embeds
)
)
``` ^^^
i stg i didnt
no, because it is exactly the same and it is a mistake from your side.
you're missing an ending ) when you append
im really confused
ah
its the EXACT same code just a different member given
thanks carrot
👍
useless print statements always making me delete stuff that doesnt need to be deleted smh
you are creating a new account for the user in both the cases, even when the user if in the data, it cant create 2 accounts for the same id
I thought you were a beginner for a second Kayle
@red blade
😂
I am really disappointed.
undisappoint yourself
aight
frick im dumb
*undisappoints myself*
well , reading that they said json is a database in some ways got me.
I use json as a database
piss off
:)
create_level_account(ctx.author, ctx.guild, ctx.message)
data = get_data()
level = data[str(ctx.guild.id)]["users"][str(ctx.author.id)]["level"]
await ctx.send(f"You are level {level}")
else:
create_level_account(user, ctx.guild, ctx.message)
data = get_data()
level = data[str(ctx.guild.id)]["users"][str(user.id)]["level"]
await ctx.send(f"You are level {level}")
``` wtf this still doesnt work!?
I saw
smh sorry
if user is None:
create_level_account(ctx.author, ctx.guild, ctx.message)
data = get_data()
level = data[str(ctx.guild.id)]["users"][str(ctx.author.id)]["level"]
await ctx.send(f"You are level {level}")
else:
data = get_data()
level = data[str(ctx.guild.id)]["users"][str(user.id)]["level"]
await ctx.send(f"You are level {level}")
see the indents
happy eevee
xD
if active:
print("lovely indents")
how do I use this
Hm
how to air
I'm sorry
he is
wait really
Get the VoiceChannel object and use the members attribute
wtf
I thought he was an expert
caeden
no.
how do I use this
is that another one of your roasts
😐
.
i mean there are docs
THEY DON'T HELP.
Uhm
they do help
cant argue
I love the docs
voice_channel_members = voice_channel.members where voice_channel is an instance of discord.VoiceChannel
how do i use discord.VoiceChannel.members
U need an instance of voice channel with guild.get_channel
ohhh
Yeah that's what I told
guild.get_channel(id).members
okay thank you
channel = guild.get_channel(ID)
members = channel.members
Caeden
Remember it returns a list of Member objects
when did you start learning Python
so..
I'll start from tomorrow 
ok
I'll learn python as well
nice
I started coding 4 years ago, dropped it and then came back to it like 2 years ago on and off. I started discord.py 6/7 months ago
I thought you knew
python is sooo easy
How so

If you want to get the names of the members then jus loop through the list
and get it
make a game
for i in ctx.author.voice_channel.members:
print(i)```
done I coded python
i cant do this?
smh
yeah
I made a cool game ima call it Minecraft
ghost pinged
You can use VoiceState then
Minecraft was made in Java
oof
!d discord.VoiceState
class discord.VoiceState```
Represents a Discord user’s voice state.
cheap Minecraft otherwise
so like
goddammit Eevee I can use ursina if I want
lmao
members = ctx.author.voice.members
names = [member.name for member in members]
@proven aurora
🙂
VoiceState returns a lot of data about a Members state
Like the voice channel they joined
Channel ID, are they deaf, are they afk
Etc etc
It has attributes that you can use to your will
how to air
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'members'
okay
!d discord.VoiceState
class discord.VoiceState```
Represents a Discord user’s voice state.
if you're a certified discord dev why are you not googling stuff 🤔
voice.channel.members
members = ctx.author.voice.members
names = [member.name for member in members]
print(names)```
My bad
please dont give information about stuff you don't know.
quietly leaves the room
!d discord.VoiceState.channel
The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
it worked
There you are
yea
enters the room
thank you
no.
ok
Stop assuming people's knowledge just because they made a simple mistake, I can do that same with you too
Moving on
!e None
LEARN PYTHON
!d None
None```
An object frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to `None` are illegal and raise a [`SyntaxError`](https://docs.python.org/3/library/exceptions.html#SyntaxError "SyntaxError"). `None` is the sole instance of the `NoneType` type.
what
Ok
lmao
i just wanted to see what it returned
!e
None
@velvet tinsel :warning: Your eval job has completed with return code 0.
[No output]
see
😛
goddammit ! a
:)
Nice name
thanks, if that was for me, someone called my cat bonbons and I just went for it
Hm, why am I getting this error guys?
1 million dank memer coins :kek:
you cant send messages to the bot?
couldn't send hey, also thats advertising lol
💀💀 💀 💀
Its my server lol
Yeah but real
code
code
i've 9
🥺🥺😈😈
!ot
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
Me who doesn't use dank memer
Um
Dm me please
Uhhh, I wasn't doing the ot command anyways
me too
goddammit
wait what.....
It's cz of your error handler
Send it here
smh
Why u saying no to him tho 🤨
def code():
"""this is a code"""
obviously this didnt come from me, but one could recommend scripting it
Don't make this channel off topic
by using your macro skills
!ot yes here <
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
!ot @velvet tinsel @manic wing
I don't really care
Pinging mods would work though
is it ok if I call you hth
Facts
should I do it
Can ya stop this? @velvet tinsel
ok
Let's keep this on topic
yes
Post your code
ok
discord bots
I like discord bots
async def _gstart(self,ctx,timee,winners:typing.Optional[str],*,message):
message is a required argument that is missing.
,-,
U didn't specify message arg while invoking the command
pep 8....
yeah i know its supposed to be for the winners to be optional
PEP8 would like to talk to you
best coder alive
you should pass something to message , its because you had the * out there , also for the love of python , follow pep8 guildines
U can't. Then keep winners at the last
!d discord.ext.commands.Bot.wait_for || I recommend using wait_for instead of passing mulitple args which may confuse the user.
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
No, thanks
k ty
wth
?
??
I just told a simple answer to them
you can just set a default value
yea i know thats what i did
should i just format it like time message winners

async def _gstart(self, ctx: commands.Context, timee, winners: typing.Optional[str], *, message: str=None):
Pass something default to make it optional
In this case, if you don't pass a message anything the message arg, it will defaulted to None
humor is finished
thank you
Don't blame me
this server is way better than dpy
blame your other worldly self?
well , its a bit less strict than dpy
and mods here are more mature
Less toxic

i got made fun off then i swore at them and got banned
Yea ig
ok
kk
Yea lets not make this OT again. I'mma be shut 🤐
the message was none
oh wait
If you didn't pass anything then it is None by default
hmmm
!e
def func(a: str, *, b: str = None):
print(f"{a}, {b}")
func(a="hello")
yea
!e
def func(a: str, *, b: str = None):
print(f"{a}, {b}")
func(a="hello")
@untold token :white_check_mark: Your eval job has completed with return code 0.
hello, None
Im getting this one again
How do I get something that isn't defined yet? like is it possible```py
class A(discord.ui.View):
def init(self, msg):
...
#somewehre else
await ctx.send(content="Test", view=A(...)) #i want this send function to be the argument in A
how would i make it so that i could do the message first instead of the winners then
!e
def func(a: str, *, b: str = None):
print(f"{a}, {b}")
func(a="hello", b="world")
@untold token :white_check_mark: Your eval job has completed with return code 0.
hello, world
See
I mean if you got made fun off thats kinda your fault lol
How can I do language packs on my Discord Bot? 😄
What's that?
yea so how would i do the message instead of the winners
Not knowing enough python there can be.. 😬
I guess just use a translator module?
^^
i want people to choose their language and it will go with the stick
Uhhhh I don't think so
i want to create a image manipulation command. which takes user's pfp and make sth like this. idk how to get this effect. its not blur filter, may be speed filter idk
U wanna pass the message u gonna send, to A right?
sry to barge in in middle
ah man :(
!pypi PIL
yes
ik that
just dont know wow to get that specific filter
kinda in need of google search query for that
it doesnt look like a filter
more like another image, even if it is a filter thats some impressive code lol
so. There would be a panel like in mee6 to change the language of the bot. When I write, for example, he will write in German.
ah
i think you gotta do that manually
U need to use a translator module
or that
no that ofc was made with photoshop
i wanna recreate that with code
use pillow then
Type all the text in a single file and just translate those before sending to the channel
how?
I also tried that when I click on the inv link, the bot is on the page in several languages, and so on. So far, the English and Hungarian are ready.
Make a file something named
#constants.py
ALL THE TEXTS OF ALL THE COMMANDS AND STUFF
And before passing those to a command, just translate all that text into another language
Don't manually write all those translations u gonna get bored in a day
if I wrote everything in it so I could swap it for those texts? I tried yesterday but did not recognize the texts in main.py
Wym
what
why not have them in a class ?
its used in @unkempt canyon
sure in the constants file
bot/constants.py lines 247 to 255
class Colours(metaclass=YAMLGetter):
section = "style"
subsection = "colours"
blue: int
bright_green: int
orange: int
pink: int
purple: int```
@client.command(aliases = ['purge', 'delete']) async def clear(ctx, amount: int = 1): await ctx.channel.purge(limit = amount)
why this not work
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
error ?
sure run it
and its not work
client = commands.Bot(command_prefix = "#", intents=intents)
i just need type #clear 5
but its clear nothing
Oh
I see
Remove the int
And add await ctx.purge(limit = int(amount))
So like async def clear(ctx, amount):
Try that see if it works
thats not work
@client.command(aliases = ['purge', 'delete'])
async def clear(ctx, amount):
await ctx.purge(limit = int(amount))
you meant like this?
It's just an example tho
its ctx.channel.purge
how come it's not raising an error though
@commands.cooldown(1, 6, commands.BucketType.user)
@commands.has_permissions(manage_roles=True)
async def delete(ctx, limit: int):
await ctx.channel.purge(limit=limit+1)
purgeMessage = await ctx.send(f"Purged {limit} messasges ")
await asyncio.sleep(3)
await purgeMessage.delete()```
ctx.purge also works
Oh hmm
Since commands.Context subclasses abc.Messageable too
Ouh yeah
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "/home/runner/bonbons-1/cogs/fun.py", line 73, in on_message
if not mention_data["reason"]:
KeyError: 'reason'
``` I'm using `not`, why is it giving a keyerror
indents 😵💫
You could also use the delete_after kwarg
That key doesn't exist
but i used not shouldnt it work?
Nope, not only flips the boolean value
he does not use the tab key 💀
it just autoindents it.
o
You could use dict.get
@slate swan I miss you 😦
hello
!d dict.get
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
cant, it isnt a python dict
yep
not inactive, im trying new stuff
like what im starting to get bored with coding
i do wanna check out nextcord and stuff 🤔
I dont do dpy that much anymore but I’m still around
Just existing
In the shadows
if message.mentions:
for member in message.mentions:
mention_data = await afk_db.find_one({"_id": member.id})
if mention_data:
if member.id == mention_data["_id"]:
if not mention_data["reason"]:
await message.channel.send(
embed=disnake.Embed(
description=f"{member.mention} is AFK. Since <t:{mention_data['timestamp']}:R>"
),
allowed_mentions=disnake.AllowedMentions(
everyone=False, users=False, roles=False
),
)
else:
await message.channel.send(
embed=disnake.Embed(
description=f"{member.mention} is AFK: `{mention_data['reason']}` <t:{mention_data['timestamp']}:R>",
color=message.author.top_role.color,
),
allowed_mentions=disnake.AllowedMentions(
everyone=False, users=False, roles=False
),
)
else:
break
else:
``` hmm how do I fix this then
because dict[key] will either return the value or exception. use dict.get which will return None by default if its not in the dict
Sh 🍝 code
clever insult
Then what is it?
A json db :dab:
a mongodb object
Nvm
i cant use get, it isnt a python dict
!d getattr
getattr(object, name[, default])```
Return the value of the named attribute of *object*. *name* must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, `getattr(x, 'foobar')` is equivalent to `x.foobar`. If the named attribute does not exist, *default* is returned if provided, otherwise [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError "AttributeError") is raised.
Note
Since [private name mangling](https://docs.python.org/3/reference/expressions.html#private-name-mangling) happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with [`getattr()`](https://docs.python.org/3/library/functions.html#getattr "getattr").
Myxi is going god mode
Is it a dict like object?, You could use it on any dict subclasses
yes
i suppose
It seems like a dict like object so it should have a get method
if not, getattr should work
it does, kinda
dunno if find is the same has get
this should work right?
data = getattr(mention_data, 'reason')
if data:
...
if not data:
...
it should, if its not overwritting the dunder method of it
guys i want to make a leaderboard command for my server for the economy commands , its basically the ppl who has the most coins, shud come at the top
@commands.command()
@commands.guild_only()
@commands.cooldown(1, 2, commands.BucketType.member)
async def help(self, ctx,aliases=["h"]):
author = ctx.author
emoji = ":white_check_mark:"
msg = ctx.message
embed=discord.Embed(title="title", description="description", color=discord.Color.blurple())
embed.set_author(name="Help", url="https://google.com")#, icon_url=self.bot.avatar_url)
# embed.set_thumbnail(url=self.bot.avatar_url)
embed.add_field(name="[Need more help?](https://google.com)", value="value", inline=False)
embed.set_footer(text="footer")
await author.send(embed=embed)
await self.bot.add_reaction(msg, emoji)```
how could i add a reaction to the message?
Getting an attribute of an object and subscripting it (eg: obj[val]) are different
Guys, so the thing is I want to make the buttons keep working for 60 seconds and then they should stop working but how would I do this ,-,
current code:
res = await client.wait_for("button_click")
if res.user == ctx.message.author and ctx.message.channel == res.channel:
if res.component.label == "General":
await res.send(embed=genEmbed, components=buttons_for_help)
elif res.component.label == "Moderation":
await res.send(embed=modEmbed, components=buttons_for_help)
You could set a timeout maybe?, Depends on the lib you are using
use a fork or dpy 2.0 for timeouts
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "/home/runner/bonbons-1/cogs/fun.py", line 73, in on_message
reason = getattr(mention_data, "reason")
AttributeError: 'dict' object has no attribute 'reason'
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "/home/runner/bonbons-1/cogs/fun.py", line 73, in on_message
reason = getattr(mention_data, "reason")
AttributeError: 'dict' object has no attribute 'reason'
its a dict
hm ok
use get
hm ok
It seems to be a normal python dictionary
My bot is already made in the old dpy version (whatever version it was)
discord_components ,-,
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "/home/runner/bonbons-1/cogs/fun.py", line 87, in on_message
description=f"{member.mention} is AFK: `{mention_data['reason']}` <t:{mention_data['timestamp']}:R>",
KeyError: 'reason'
``` same issue as earlier
That key doesn't exist.
reason = mention_data.get('reason') <= used this
how can i get the attached image using ctx.message.attachments? im pretty sure it returns a list, so how can i make it so the image attached in the message is actually usable?
but i used if statements to control the error
mention_data["reason"]
that doesnt exist
OH WAIT
What?, I can't see any if statements
@commands.command()
@commands.guild_only()
@commands.cooldown(1, 2, commands.BucketType.member)
async def help(self, ctx,aliases=["h"]):
author = ctx.author
emoji = ":white_check_mark:"
msg = ctx.message
embed=discord.Embed(title="title", description="description", color=discord.Color.blurple())
embed.set_author(name="Help", url="https://google.com")#, icon_url=self.bot.avatar_url)
# embed.set_thumbnail(url=self.bot.avatar_url)
embed.add_field(name="[Need more help?](https://google.com)", value="value", inline=False)
embed.set_footer(text="footer")
await author.send(embed=embed)
await self.bot.add_reaction(msg, emoji)```
how could i add a reaction to the message?
oh fuck i made it the wrong way
i never showed it
Command raised an exception: AttributeError: 'Bot' object has no attribute 'add_reaction'
also it woukd be better if you use .format method there its just too ugly imo
msg = await author.send(...)
await msg.add_reaction(...)```
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
^^
but I don't think it'd be pretty though```py
await message.channel.send(
embed=disnake.Embed(
description=f"{member.mention} is AFK. Since <t:{mention_data['timestamp']}:R>"
),
allowed_mentions=disnake.AllowedMentions(
everyone=False, users=False, roles=False
),
)
my send func already has too many kwargs
declare two variables for those, it will look better
mention_timestamp = mention_data["timestamp"]
ah ok sure ig
code
also yes, it will look simpler if you do smth like,
mention_timestamp = mention_data["timestamp"]
embed = discord.Embed()
embed.description = ...
channel.send(embed=embed)```
hmm ok
await message.channel.send(
embed=disnake.Embed(
description=f"{member.mention} is AFK. Since <t:{mention_data['timestamp']}:R>"
),
allowed_mentions=disnake.AllowedMentions(
everyone=False, users=False, roles=False
),
)


