#discord-bots
1 messages · Page 703 of 1
@bot.event
async def on_member_join(member):
guild = bot.get_guild(917821802351308910)
channel = guild.get_channel(917826956295303219)
embed = discord.Embed(title=f"**{str(member)}** has joined the server.",color=0x2f3136)
await channel.send(f"{member.mention} <@&917950907445039154>",embed=embed)
without ()
dont call it
alr
@shrewd inlet do you have member intents enabled?
yep
"Required for your bot to receive events listed under GUILD_MEMBERS."
okay good
#help-lollipop pls someone if anyone knows
if you want you can make the embed constructor look better
how
embed19 = discord.Embed(
title="",
description="",
color=,
timestamp=)
o
this didn’t work
someone joined and it didn’t work
nvm
what do you mean by "it didn't work"
nothing happened pretty much
add a print statement to it and see if it gets called
if it doesn't we can diagnose it to an intent issue
if it does it's most likely with your code
where do i put print()
after the event
@bot.event
print(async def on_member_join(member):
guild = bot.get_guild(917821802351308910)
channel = guild.get_channel(917826956295303219)
embed = discord.Embed(title="**{str(member)}** has joined the server.",color=0x2f3136)
await channel.send(f"{member.mention} <@&917950907445039154>",embed=embed))
so that??
i’m new to this srry
@bot.event
async def on_member_join(...):
print(...)
...
do you have logging setup
@bot.event
async def on_member_join(member):
print("works")
guild = bot.get_guild(917821802351308910)
channel = guild.get_channel(917826956295303219)
embed = discord.Embed(title="**{str(member)}** has joined the server.",color=0x2f3136)
print("works1")
await channel.send(f"{member.mention} <@&917950907445039154>",embed=embed)
nvm
alright i copied that
now do i make a member join
yes
maybe i need to import something
nothing happened
nope
show your bot constructor and your intents vars
bot = commands.Bot(command_prefix=";",help_command=None)
Makes sense
???
lol
You didn't pass in intents
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
bot = commands.Bot(..., intents=discord.Intents.all())
for testing only
it gives you all intents, for production you should limit your intents to what you need
if you have something like
intents = discord.Intents.all()
bot = commands.Bot(..., intents=intents)
then yes
This also works
Traceback (most recent call last):
File "main.py", line 10, in <module>
bot = commands.Bot(command_prefix=";",help_command=None, intents=discord.Intents.all)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 98, in __init__
super().__init__(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1107, in __init__
super().__init__(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 248, in __init__
self._connection = self._get_state(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 265, in _get_state
return ConnectionState(dispatch=self.dispatch, handlers=self._handlers,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/state.py", line 152, in __init__
raise TypeError('intents parameter must be Intent not %r' % type(intents))
TypeError: intents parameter must be Intent not <class 'method'>
It might be intents=discord.Intents().all()
.all() is a @classmethod so I suppose that makes sense
Also may I suggest you put your gracie_* variables inside a seperate .json file
Traceback (most recent call last):
File "main.py", line 110, in <module>
bot.run(os.getenv('TOKEN'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
172.18.0.1 - - [24/Dec/2021 00:26:10] "GET / HTTP/1.1" 200 -
ooohh alr
Yeah go to your bot's dev portal and enable it
alr enabled
now try
Sure
oh nvm someone joined tysm
how do i fix that 😭
So I assume it worked
use an f string for the embed title
also you don't need to do str(member)
just member will do
and it will also show the discriminator?
correct
!resources You can find numerous guides to learn Python here. Please, do not jump onto advanced libraries, such as discord.py with almost no knowledge in Python nor programming itself.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ty
you don't need the parenthesis, this will do:
print(f'{member} joined the server')
discord.Member has a __repr__ dunder which allows you to do that
oh it finally worked :D thanks!
__str__*
__repr__ seems to do the same thing as well
!e
class MyClass:
def __repr__(self):
return "Test"
print(MyClass())
@sick birch :white_check_mark: Your eval job has completed with return code 0.
Test
!e
class MyClass:
def __str__(self):
return "Test"
print(MyClass())
@sick birch :white_check_mark: Your eval job has completed with return code 0.
Test
¯_(ツ)_/¯
I assume the difference in functionality shows up once you start having string concatenation and f strings and str()
discord/user.py lines 90 to 94
def __repr__(self) -> str:
return (
f"<BaseUser id={self.id} name={self.name!r} discriminator={self.discriminator!r}"
f" bot={self.bot} system={self.system}>"
)```
Well, __str__ and __repr__ both do the same thing, and that is to return a string representation of whatever. The only difference is repr is mostly used for debugging whilst str is used for regular user use
that's what __repr__ returns
Oh yeah debugging
makes sense
Though does __str__ take precedence over __repr__? I don't think I remember seeing that little segment when printing a user object
Uhhh, that would be hard to find out unless otherwise documented. It mainly depends on what function you are actually doing to call the type's __repr__ and __str__
E,g if you did repr(class) it would call __repr__, if you called str(class) it would call __str__, if you called print(class) it would call __str__
And for the last case, i.e the print it would call __repr__ if no __str__ dunder is implemented on the class
Otherwise it would call __str__ first
So in the case of the User object, __str__ takes precedence over __repr__ when printing
yea, if __str__ is provided then python will use __str__, else they will use __repr__, so __str__ should take precedence over __repr__
What does it exactly mean to take precedence here
It would depend on what you call in order to call __str__ or __repr__
E.g repr would call __repr__, str would call __str__
There is no real hierarchy to see
maybe like __new__ and __init__, __new__ takes precedence over __init__
Yea, but __new__ and __init__ aren't __str__ and __repr__ are they?
.. No..
Yes, and the hierarchy with __new__ and __init__ are different from __str__ and __repr__
__new__ creates the instance, __init__ initializes the instance
Meaning __new__ HAS to be called first, it isn't like __str__ and __repr__
There isn't really a hierarchy with __str__ and __repr__. Whichever one gets called is called

so what do they mean..
__str__ and __repr__ don't take precedence over another, it depends on what you call
E.g print -> str -> repr
__str__ produces a user-friendly string representation of an object, while __repr__ as a general rule should be more detailed and should allow you to 'remake' the object from the string
print will call __str__ if it exists, else __repr__ if it exists and __str__ doesnt
But that's only due to print any other call can have different effects
Thus they don't have a hierarchy
if msg.author.id == id:
return
what would this return?
and what if its false?
To end the function
but if its true it would continue right?
if it's False
the return keyword would return back to the function call if the if condition was True.
if it's True then it will execute return
and if its false nothing would happen right?
if you dont have other code after that if statement then no
but if you really dont, then the if statement would be useless
but what if i do and the if statement is false?
then go to the next code
And if there is no next code it just returns None
@bot.event
async def on_message(message):
if message.author.id == id:
return
await channel.send("ok")
ok so this would respond to any message and if the if statement is true it will continue but how so if return ends the execution of a function and if its not true it doesnt do anything thats whats raising my question mostly
!e py def foo(x): if x == 1: return print("X was not 1") foo(2)
@patent lark :white_check_mark: Your eval job has completed with return code 0.
X was not 1
the if statement returned false so it executed the "next code" which was my print statement.
yeah i know but i dont understand what i said on the top
if the if statement is true it would simply return?
yes and it should stop the execution right?
yes
yep
then why in dpy if the if statement is correct it will continue the code as if the if statement were false but if the if statement is false then it would just stop the execution as if the if statement were true
thats not a discord.py related issue, python is python in any library.
and it doesnt, if that if statement returned true then it would execute the return
why do you think its doing the opposite of whats supposed to happen?
well if the author of the msg is the bot it would continue right like a check but if it were false it wouldnt do that why so
you have if message.author.id == id in this case, what is id?
the bots id
if the bot is the author is should return
but there is a more simple way to do this
a simple if message.author.bot would also work
No it wouldn’t
if i have a for loop that is inside of a function can i do return to stop the for loop but not the funcion
why so?
oh wait your right
if message.author == bot.user:
this will see if author is a bot, not author is the bot
@patent lark @visual island sorry guys i had a massive brain fart again jeez im stupid

?
use break keyword
sorry im like that
right, i was going to point that out, it checks for any bots, but it does work in the sense that this person wants it too.
but that probably wasnt the best example since it would do more than what they're asking for
so like this?
@visual island :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
Yooo guess what
wut
HunAI got verified lessgooooo
Thanks!!!
you know you could just... guild.get_role(id) ?
Wait so what would it look like
.add_roles(guild.get_role(12345))
@mellow gulch ^
also.. you could store the ids in a dict and call them instead of having a bunch of elifs?
dict?
!d dict
class dict(**kwargs)``````py
class dict(mapping, **kwargs)``````py
class dict(iterable, **kwargs)```
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
Dictionaries can be created by several means:
• Use a comma-separated list of `key: value` pairs within braces: `{'jack': 4098, 'sjoerd': 4127}` or `{4098: 'jack', 4127: 'sjoerd'}`
• Use a dict comprehension: `{}`, `{x: x ** 2 for x in range(10)}`
• Use the type constructor: `dict()`, `dict([('foo', 100), ('bar', 200)])`, `dict(foo=100, bar=200)`
imma not make a class so...
I want to get the cooldown of a command that the user is requesting help for. If the user uses the command "!help dice_roll" and if dice_roll has a cooldown, I want that to be displayed in the response embed for my subclassed help command. How do I get that?
command._buckets._cooldown gets the cooldown of a command
you can get either rate, per, or type
Like this? f”cooldown: {command._buckets._cooldown}”
yes
but you should get it's attribute which is rate, per, or type. Or you will get CooldownMapping object
What’s that?
@bot.command()
@commands.has_permissions(ban_members=True)
async def mute(ctx,member: disnake.Member,time: float = None ,*,reason=None):
if reason == None:
reason = 'Spamming! '
if time == None:
time = 900
muted = (f'You have been muted in ' + f'{ctx.guild.name}' + ' for ' + str(time) + ' seconds' + ' because of ' + reason)
await member.send(muted)
await ctx.channel.purge(limit = 1)
await member.timeout(duration=time,reason=reason)
if time >= 60:
time = time/60
await ctx.channel.send(f"{member} has been muted for {time} minutes because of {reason}")
else:
await ctx.channel.send(f"{member} has been muted for {time} seconds because of {reason}")
This is a timeout command that works perfectly
it's better to use timestamp imo
await ctx.send(f"{member} has been muted until <t:{int(datetime.datetime.now().timestamp() + time)}:R>")
No it’s not
😂
Oh that's a good idea tbh, I need to change that in some of my existing discord bots
the new timestamps are awesome
use ctx.message.delete instead of purge.
you also dont need to compare against none, you can just do
if not reason:
reason = "Spamming!"``` 
and even if your comparing, is None should be used
just provide directly in the params
Honestly this guy(Wiser) has just been being a nuisance all day. Hes been "helping people" or trying. and everytime he would say something it would either be "yes" or "no" and when prompted for an explanation he refused.
Basically hes trolling
ooh
Someone actually trying to help would say something and he would always disagree and say "no thats wrong" or "no its not" and not say anything after that.
honestly tho timestamps are better tho. As far as ux
Or, reason = reason or "Spamming!"
That way if reason is not truthy, E.g None, it will set reason to "Spamming!"
@bot.command()
@commands.has_permissions(timeout_members=True)
async def mute(ctx, member: disnake.Member, time: float=None, *, reason="No Reason Provided."):
muted_till = f"<t:{int(datetime.datetime.now().timestamp() + time)}:R>"
await member.send(f'You have been muted in {ctx.guild.name} till {muted_till} for {reason}')
await ctx.message.delete()
await member.timeout(duration=time,reason=reason)
await ctx.channel.send(f"{member.name} has been muted till {muted_till}")
(indentation might be off, wrote it here itself)
Bro your always shit posting wtf
@pliant gulch @visual island any other suggestions 
so much await 
make time none

so if the time isnt given it will unmute him
might be a little confusing though, for example if you just want to mute them for once and think about time later
unmute command: am i a joke to you?
reason = reason or "spamming", ez
Ig this one's better
bot.command()
@commands.has_permissions(ban_members=True)
async def mute(ctx,member: disnake.Member,time: float = None ,*,reason=None):
if reason == None:
reason = 'Spamming! '
if time == None:
time = 900
await ctx.channel.purge(limit = 1)
await member.timeout(duration=time,reason=reason)
if time >= 60:
timee = time/60
rem = time % 60
time2 = math.floor(timee)
await ctx.channel.send(f"{member} has been silenced in the class for {time2} minutes and {rem} seconds because of {reason}")
await member.send(f'You have been muted in ' + f'{ctx.guild.name}' + ' for ' + str(time2) + ' minutes ' + str(rem) + ' seconds because of ' + reason)
else:
await member.send(f'You have been muted in ' + f'{ctx.guild.name}' + ' for ' + str(time) + ' seconds' + ' because of ' + reason)
await ctx.channel.send(f"{member} has been silenced in the class for {time} seconds because of {reason}")
WHY?
like literally shortened it so much and you stretch it without reason 
You wrote de reais without closing the f string
my python version is 3.10.1
uhh
im a replit guy lol
what? how to resolve it
Not bad pretty good, heres the one I wrote in my library when I added timeout support https://gist.github.com/an-dyy/b8c81ce7f332d64e97519b07f95e76f0
!e py var = 23 print(f"you did this :{23 some random text}")
just nove the text out of curly braces
*move
- use a bot instance
- tabs and spaces cant be used inter-changeably
- either indent everything in tabs, or everything in spaces - in f-strings, {} should contain only a variable, not a string to actually print
- so you need to do, as sarthak showed, pass de rais! outside the }
modern mute 
mmm yes it was added when it got released so I didn't know what to name it
but yes very very modern, you don't need a database and a tasks.loop anymore
Plus mutes are persistent so you won't have to hook member join event
yeah its pretty good
no db, no problem if bot goes down, no problem if user leaves/rejoins
yes
They also support X-Audit-Log-Reason
So that means all mutes can be fully stored in the audit logs
WAIT
nice
It would also be quick to query the audit log since you can filter the ID and the audit log action type
Demn koala here too
So in some cases faster than a DB
Andy , you implemented .ext.commands like stuff in lefi?
I mean cogs and stuff
your making your own wrapper? 
is there any like untimeout command?
Yes but they are under a different name and have different methods and what not
Cool
Yes ofc
I implemented ext commands like the first thing in my wrapper lol
ive heard "audit logs are a pain", and slow 
Oh i see , Plugin
But my thought here is, and I might just be missing some logic but like, you can make a request to the API that has a payload with the id filter and the action type filter
Meaning you can get what you want from the audit log endpoint
Thus the speed would depend on the speeds of your internet
worked
Audit log stuff is only slow due to the library abstraction discord.py has probably
makes sense, but you would need to do the ratelimit handling yourself then
any idea on its ratelimit?
Just as paginators, iterators etc
like requests/time
I mean, I already have all ratelimiting handled in my wrapper
IF ANYTHING better than discord.py's ratelimiter
how to create a music bot?
lmao
Because unlike theirs I use Semaphores instead of Locks per bucket
Meaning concurrent requests support!
And each semaphore per bucket is set to X-Ratelimit-Limit
Meaning you get the most possible
you should learn python first.
cool
I'll check what the ratelimit is on audit logs again
I might be super high or something I can't remember

how do you check, exactly?
I'll send a request
why it trow An error occurred: Command raised an exception: TypeError: 'in <string>' requires string as left operand, not int
They don't have a specific X-Ratelimit
Thus they fall under the global ratelimit
Which means you could do 50 requests
in (time)?
Per second
ay thats more than enough imo
Yep
what does this mean
gg
read it
tried reading your errors?
but it has admin tho
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Usuario\Desktop\Bot.PY", line 19, in on_message
channelvc = message.author.voice.voice_channel
AttributeError: 'VoiceState' object has no attribute 'voice_channel'```
@client.event
async def on_message(message):
if message.content.startswith('>entrar'):
channelvc = message.author.voice.voice_channel
await client.join_voice_channel(channelvc)```
it has admin meaning it can remove roles right???
await message.remove_reaction(payload.emoji, payload.member)
Does anyone know why this wouldn't be working. I'm not getting any error so I have no idea whats happening
are u trying to remove it from someone who also has admin?
Anyone help 
that doesnt matter
i mean ig ye
oh it doesnt?
if the role is above the bots top role, it will raise that error.
you cant remove a role from someone with a top role higher than your(bot) own or equal to yours(bots)
the role cannot be managed by the bot
so there is no way for bot as admin to remove my role if i am owner
not if the role is above its top role
wdym
if the role you're trying to remove is higher than the bots highest role, it will raise that error
xd
how do i make a command without the prefix
like i want to make a normal command but i don’t want to use the prefix that i already set
you want to invoke a command without using the prefix?
i just want it to be a trigger without the prefix
yes
as far as i'm aware, you cant do that.

ofc noone can remove the owner lmfao
you could invoke a command while invoking another command, (call a command inside a command). but if you just want to randomly invoke a command, i dont see that happening
k so i did this but i have same error
can anyone help me with my yaml files?
You could handle it in process_commands
Just set the command_prefix to ""
That would affect every command though
i guess i misunderstood the task?
i thought they wanted a command to just randomly invoke.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Admin\Desktop\index.py", line 19, in on_message
channelvc = message.author.voice.voice_channel
AttributeError: 'VoiceState' object has no attribute 'voice_channel'
how to resolve this
If you want one command to have no prefix then yea, your probably have to change process_commands
Although you need to mess with more internals as discord.py validates Context if the start contains the prefix and a valid command name iirc
okay this is my 3rd day coding so i’m gonna pretend i never asked 😃
@client.event
async def on_message(message):
if message.content.startswith('>entrar'):
channelvc = message.author.voice.voice_channel
await client.join_voice_channel(channelvc)
!codeblocks
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.
it says that the bot has no permission to remove a role from someone that does not have admin yet bot have admin
ik
that role is above the bots highest role.
@client.event
async def on_message(message):
if message.content.startswith('>entrar'):
channelvc = message.author.voice.voice_channel
await client.join_voice_channel(channelvc)```
```py
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Admin\Desktop\index.py", line 19, in on_message
channelvc = message.author.voice.voice_channel
AttributeError: 'VoiceState' object has no attribute 'voice_channel'```
the bot is unable to manage that role.
Anyone help? 
the error says it all.
use member.add_roles()
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
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 added [`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.
ty
await message.remove_reaction(payload.emoji, payload.member)
Im trying to make a reaction role bot. so if the reaction isnt what its supposed to be i remove the reaction. But its not removing the reaction and im not getting any errors so i dont know whats wrong
i saw a bot that can do one command for both. so basically the same command can add and remove geh command.
example:
,role @slate swan admin
— added role
,role @slate swan admin
— removed role
check if the user already has the role
i would like to do that
print is your friend imo
your code might not be getting as far as your expecting it to reach, print each step of the way 
it is. i have a if statement right before it and its printing something thats in it
print('fard')
iterate through their roles and check for the role, if the role is there, remove it, if the role isnt there. add it. using member.add_roles() and member.removes_roles()
member.remove_roles
- get a role object firstly
- check if the user already has the role
- if yes, then remove it (member.remove_roles)
- if not, then add it (member.add_roles)
works?
member.remove_roles* member.add_roles*
yup ty
Don't need to iterate here though, just do Role in Member.roles
yeah
in is basically iterating it too 
can someone please a send a code for it, in “bot.commands” ? i’m on my phone rn ;-;
we dont spoonfeed
noone will
other than youtube tuts 
its about learning, give it a try and if you run into issues, come back.
alrighty :)
@client.event
async def on_message(messege):
try:
if message.content.startswith('>entrar'):
channelvc = message.author.voice.voice_channel
await client.join_voice_channel(channelvc)
expect discord.erros.InvalidArgument:
await client.send_message(messege.channel, "Você necessita estar conectado em um canal de voz!")```
why error?
client.send_message?
yes
the syntax is incorrect, and im pretty sure thats old code
try learning python, copying code isnt a great start to that either.
wait
Yea, but its done for you so you won't need to do for x in y
idle 3.1.0.1 bugged
i think voice.voice_channel should be voice.channel
that code is very outdated.
yes
nor is it even written correctly
i viewed this when the discord.py is from 2017
and message is spelled wrong
and the syntax is incorrect
except spelled wrong and in the wrong indentation

thats like 4 year old code?
you want to use the bot commands framework isntead

👀
because you discord
a good story
it is
---->
<---- credit card!!11 nitro
no
very good story
I dont get why umbra/maya in the dpy server didnt maintain it; they're literally the smartest people I know
hi i have a question how do made that bot dosent count bots in the member count coomand
cuz my command counts bots too
check if the member is a bot
yes ofc since its a member
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Guild.humans
(needs member intents)
!d nextcord.Guild.humans @slate swan lol
property humans: List[nextcord.member.Member]```
A list of user accounts that belong to this guild.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Intents.members "nextcord.Intents.members") to be specified.
New in version 2.0.
alright
their async knowledge are just not at Danny's point
I doubt hes using nextcord though
but i dont wonna let bot to count bots
doesnt dpy have it? oops
no, thats a new attribute in nextcord
o
this @slate swan if your using dpy
you can use guild.humans (with member intents) only if your using nextcord
oh
I was bored last time :p
is it possible to make a discord bot that finds names starting with a !
but how i made in the command thing thats checks if the member is bot
Are you trying to find korta?

str.startswith()
cuz i dont know
for member in ctx.guild.members:
if member.name.startswith("a!"):
print(member.name)
I think would work
gaming, thanks
user_id is a global variable and works fine but when I empty the user_id list it becomes a local variable so how do i keep it as a global one
but how i made it cuz i dont know how to make it
you could do something like this, not the most efficient way lol
members = []
for m in ctx.guild.members:
if m.bot is False:
members.append(m)
return len(members)
ok
apparently danny asked people who he trusted but they all declined
Global it
ok?
you dont need to tell me stuff I already know
lemmie try
sum(not i.bot for i in guild.members)
len(list(filter(lambda u: not u.bot, guild.members)))
Hey @strong sluice! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
¯\_(ツ)_/¯
you literally asked why theyre not maintaining it
fastest way
no? where the fuck did I say that
Hey @strong sluice! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
Wtf how😳
trollz
"I dont get why umbra/maya in the dpy server didnt maintain it; they're literally the smartest people I know"
OT
yeah
i never asked why they're not maintaing it
😳
🤦♂️
can be used in my code of the command i mean cuz i dont wonna made something not working propely @bot.command() async def statyinfo(ctx, info): server = ctx.guild if info == "memberCount": await ctx.send(server.member_count) elif info == "numberOfChannel": await ctx.send(len(server.voice_channels) + len(server.text_channels)) elif info == "name": await ctx.send(server.name) elif info == "rolesCount": await ctx.send(len(server.roles)-1) else: await ctx.send("Dziwne... tego nie wiem")
Where
im just not gonna say anymore. no point in argueing

So I suppose you have already defined the user_lizt variable and are defining it again so as to clear it, right?
Ye im trying to clear it
I think you ment no friends
Is there a different way to do that
😔
You can use the clear method on the list
ls = [som stuffs here]
ls.clear() #clears the list
Or maybe you should touch grass
eating it now
You aint a goat lol
kek sum(member.bot for member in guild.members)
Your more a pig
Som means…
😳
filter is faster than list comps isnt it?
what the hell, thats just indicating some data and ignore useless typos
Where am I using list comps
Oh lmao
generator*
another question
i gave an example, you implement it into your code, im not gonna spoonfeed you
how do i make a bot change someones nickname from a list i make
oh
like i want to make a txt file and put names i would want it to change to
you can read the files using readlines method or simply split it after reading it using the read method(both convert the data into a list), then use random.choice or random.randint to pick a random name
what do i do because of this lmao i dont understand
what is user_name?
you cannot append stuff for strings
Appending strings? Eh?
🤦♂️
@visual island
i just said you cant append stuff for strings 
You can concatenate strings but only append stuff into dicts or lists
!e ```py
myvar = ''
myvar.append('e')
@heavy folio :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: 'str' object has no attribute 'append'
sorry i 🤦♂️ myself
!e ```py
myvar = []
myvar.append('e')
print(myvar)
@heavy folio :white_check_mark: Your eval job has completed with return code 0.
['e']
Its alright, shit happens
what wront with code
okay 😔
!e
for member in ctx.guild.members:
if member.name.startswith("a!"):
await after.edit(nick="fart lol")
@slender perch :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | SyntaxError: 'await' outside function
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
learn basic python first
while True:
print("chicken butt")
i swore there was a when in python
i didnt use it in a while till this week
oh no im thinking of lua nvm
Oh you were thinking of lua? Haha
Which is the alternative repo for development of discord bots in python? What are their advantages?
forks like disnake , pycord , nextcord
or libraries made from scratch like hikari
out of all forks i'll suggest you to use disnake since its well maintained and used
if you want to go for something different that then og discord.py you may try hikari
you may try hikari
dude that shit doesnt even have commands
https://pypi.org/project/hikari-lightbulb
https://pypi.org/project/hikari-tanjun
lmao wtf , they have 2 of them
how can you fetch a message by it's id?
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
thx, does it require a bot.get_channel type of variable
like for example does it go like this
txtchannel = bot.get_channel(54378958347948357) # replace with channel id
await txtchannel.fetch_message(489335485348)
not even like that
I have it so that a class in a different py file is called after a msg being sent, how would i be able to use things like await without having to trigger smth like on_message to use it but only calling the class
How can I get 2.0 ?
pip install -U git+https://github.com/Rapptz/discord.py
run this statement in your terminal
using replit
🥶
then too bad
import discord
i thought i found the issue but now im in deeper shit
import discord
import os
token = input("discord token?: ")
@bot.event
async def on_ready():
for member in ctx.guild.members:
if member.name.startswith("!"):
await after.edit(nick="fart lol")
the issues are with @bot.event ctx.guild.members and after.edit(nick="fart lol")
ctx is not defined :p
dont do stuff in on_ready
Anyone
https://pypi.org/project/py-cord/
Optimised in both speed and memory.
how so? has anyone tested this?
Eh? Not really.
thats from the og discord.py
its bad
|| i fucking hate pycord so much disnake is the best module WE LOVE EQUENOS ||
^
I do love equenos but dont forget about the contributors as well we love them to
we love em all
Yes
how do you make a bot create a channel in a specific category?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
category=
depends, if you want the channel to be nsfw then you set it to True otherwise you set it to False
k thanks
this says channel: discord.CategoryChannel but idk how the fuck you're supposed to get an instance of discord.CategoryChannel without doing discord.abc.Messageable.category 
no get_category afaik
get_channel exists
but, thinking about ti discord.abc.Messageable.category would be fine
:O
Wdym module?
well, it says that it doesnt exist
Should be
await bot.create_text_channel("channelname")
Yes
ty
AttributeError: 'Bot' object has no attribute 'create_text_channel'
*guild
it must be Guild.create_text_channel
it then says guild doesnt exist
.... just use ctx.guild.create_text_channel 😐
how do y'all make your help cmd
i use commands.MinimalHelpCommand()
yes i subclass it xd
commands.HelpCommand 🏃♂️
So quick question. When discord adds a new feature (in this case, timeouts) how long does it take for discord.py to get such a feature? Is it instant?
discord.py wont get it , its no longer maintained
Never. It's unmaintained.
!d disnake.Member.timeout disnake added it already
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
It used to be pretty fast when it was maintained tho
Danny always kept up.
Eh there were other good reasons
mhm
async def on_message(message):
message.content = message.content.lower()
if message.author == client.user:
return
if message.content.startswith("sheep"):
await message.channel.send("Hello Sheep")```
could anyone maybe help me as to why this isnt working :(
I dont get any errors but it doesn't work either way
@bot.command()
async def hylo(ctx):
if ctx.message.author.id == '873139718450188328':
await ctx.message.channel.send('Greetings, father')
it doesnt respond to me :c
i tested it by adding an else statement and sure enough it did the else
You compared an int with a string
As tylerr said, just remove the quotes.
damn im dumb
@bot.command()
async def hylo(ctx):
if ctx.message.author.id == 873139718450188328:
await ctx.message.channel.send('Greetings, father')
Will do.
yep i fixed it thanks
is there another on_message in your code?
yes
thats why
hmm
put them in the same event
got it working now, thanks a lot!
so this is my code and i was wondering if the message content was something, return a response, if the message content was something else, return a diff response
@lets.command()
async def play(ctx):
randomnum = random.randint(0, 10)
await ctx.reply("Alright, I've got guessingGame and that's it, wanna play it?")
def check(m: discord.Message):
return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id and m.content == randomnum
try:
await ctx.reply("I just chose a number between 0 and 10. guess it whilst you can")
await bot.wait_for(event='message', check=check, timeout=30.0)
except asyncio.TimeoutError:
await ctx.reply("you are afk i guess")
else:
await ctx.reply("y won?")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('sheep')
await message.channel.send('Hello Sheep')
if message.content.startswith
....
np
not the best practice, use elif message.content.startswith
When bot adds 30+ emotes to an guild the bot cannot add anymore emotes to the guild after ~15 emotes. I assume this is because the bot is getting ratelimited (?)
What would be the way to go about this other than introducing an asyncio.sleep(...) internally in the bot?
elif statements best statement
yeah but from what I gather Llama is a beginner so not yet
in discord.py or python itself? 💀
elif is a python thing
ik
idk
anyways will some1 help
check the message content
my question, how
is it possible to log deleted images or just generally any image sent
sure
!d discord.Message.attachments
A list of attachments given to a message.
property url: str```
Returns the underlying URL of the asset.
attachments return list of discord.Attachment not Asset
!d discord.Attachment
I never knew that existed
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.
now you know 😉
in this case what will the msg kwarg do exactly
it's be lmfao, and it'll be a discord.Message object not do
whats randomnum
reread code
dis
it'll be a random.randint object then
oh
does the msg kwarg just check the message content or are there more steps required
what
the msg kwarg is the message object
it doesn't "check" the message content
you'll have to do that yourself
doing that in a command is tough especially with a await bot.wait_for 😓
because that's literally my question, how would i check the msg content
its just if statements though
in the check, it's not an asynchronous function tho
so i can't use await
message = await bot.wait_for(**kwargs)
if message.content == ...:
...
what
fuck that makes sense
yes
I am going to do one push up every time I forget to await something.

how i make anime gif command ( api send anime gifs)
ok so this is a pretty dumb question but i've got this command: rule 1 but ive got commands like that up to rule 15 and whenever I do 10,11,12,13,14 and 15 it shows rule 1 too, so how can I prevent that from happening?
if message.content.startswith('rule 1'):
stuff
...
put the 10 until 15 in the top and 1 in the bottom
find an api which provides gifs, request it, parse the data, get the file/url of the gif, send it
ez 
@visual island pls help
Why don't you just have one rule command that takes an argument?
@bot.command()
async def foo(message):
if message.channel == message.author.dm_channel:
if message.content.startswith('foofoo'):
await message.author.send('foofoofoo')
doesnt work
I fixed it, thanks tho
can someone help with this
What are you even trying to do
trying to get it to respond in dms
you can use isinstance or dm_only check
hmm
!d discord.ext.commands.dm_only use this decorator and the command will work only in dms
@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.
This check raises a special exception, [`PrivateMessageOnly`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.PrivateMessageOnly "discord.ext.commands.PrivateMessageOnly") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
New in version 1.1.
thx
How would i write an event that when a bot gets invited to a new server, it should automatically create its own role in that server
it already does
you mean the roles that bot get similar to their name?
yeah
if you invite bot with any perms. The bot will get the role
Use disnake.ext.commands.dm_only then
yep i did
strange, will check on the perms then, cuz mine doesnt create a role for itself
Show code
"invite it with perms"
not add perms after adding it
oh i see
@disnake.ext.commands.dm_only()
async def foo(message):
if message.content.startswith('foofoo'):
await message.author.send('foofoofoo')
I dmed the bot saying foofoo but not response
where would i change those settings
if there is a mistake, i assume it's in the await
why did you remove the @bot.command decorater?
i didnt, i just didnt include in message
oh bruv I mispelled command
i wrote commamd...
yeah still nothing
And yea why will the message.content.startwith with foofooo when u use it with prefix
subclassing
^, because of this gist i now use minimalhelpcommand regularly
hm
So my bot got verified and with it, it also got Members and Messages Intents!!!
(Tho I use Members intent only for bot.users)
congratulations :dogepray:
yay
good morning, Eevee
haiiiii, morningggg
in England?
its afternoon here...
u from india?
yeah, why?
nah
!ot
no me too from india LOL
lol
!ot

Lol
Ping
Pong 🏓 ! 104 ms
0 ms
So you live in the discord headquarters?
💀
hey
just curious, how would I handle different CheckFailures?
if isinstance(error, commands.CheckFailure):
This just handles ALL Check Failures
you would make custom error inherited from CheckFailure
so for example
class MyCheckFailure(commands.CheckFailure):
pass
def my_check(...):
if True:
...
else:
raise MyCheckFailure
```or something like that
then in your error handler
if isinstance(error, MyCheckFailure):
...
I see. And I would just make a new class for each type of check
yes
Cool thank you very much
👍
Just a little improvement it'd just be MyCheckFailure instead of commands.MyCheckFailure
@visual island your github username reminds me of a very toxic server owner
thanks. will check them out!
hi can anyone help me with deferring and the followup webhook
and their name is icy?
its pip install discord.py
That's not the issue
yeah install python
Or install pip
its the next issue that will come after installing python lol
yeah
@tiny ibex so how to fix?
It won't
!pypi discord
A mirror package for discord.py. Please install that instead.
discord exists
@red sundial @red sundial
Reinstall python
damn i didn't know that
Yup
yeah and set it to path while installing
Yes
Help me please
Or locate pip
just delete python
Wait first try to locate pip
how
If you can't find it then reinstall
and install it again, while installing you'll see a option with Set to PATH, tick that and installl
Idk how
@tiny ibex
1 min
How to uninstall py
Don't
C:\Users\your-username\AppData\Local\pip
It should be here
@proper acorn
Bruh i did sr
And?
Is it normal that guild.create_custom_emoji does not raise any error when the guild cannot accept any new emojis?
Wait
It wasn't there?
Or is it a bug 
@tiny ibex
??
Then reinstall
Just run the python installer
Then choose uninstall python
Then run again and install
Make sure to add it in path\
I mean i just re-install but still cant
Which python version??
Lemme try ur
@tiny ibex
Install python 3.8 or lower
Python 3.9 and above doesn't support windows 7
That's your issue
Tysm lemme try
Hmm
Ok I'm runnin into some trouble with my custom error handler
wait try python3 -m pip install discord
or pip3 install discord
try pip3 install discord then
nope
their name is flame
hes a partnered server owner
ohh, my github username. Didn't saw that correctly. But yeah many people are toxic these days
wait, you're kayle I've just realized it
bro try py -m pip install discord then
Have you installed Python to PATH?
yep
@commands.command(aliases = ["eightball", "eightBall", "Eightball", "8ball"])
async def eightBall(self, ctx, *, question):
embed = discord.Embed(title = "8ball result", description = "Result of the 8ball command", color = discord.Colour.random())
embed.add_field(name = "Question:", value = question, inline = True)
embed.add_field(name = "Reply:", value = self.eightball(), inline = True)
await ctx.send(embed = embed)
``` why is the aliases not working, it shows command not found in the console when I write "8ball" even though its in the aliases
is the function inside the class
Is the cog loaded?
By the way, you can pass case_sensitive=False in your bot's constructor. That'll let you avoid adding aliases in multiple cases.
alright, thanks
insensitive*
!d discord.ext.commands.Bot case_insensitive
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.
Ah right. Haven't used dpy in a while; hence I forgot. 
thanks
excuses, excuses.
how do it fix this ?
Do not import bot.
what the hell is bot module
wow
you dont need to import bot
SyntaxError: Non-UTF-8 code starting with '\xe2' in file C:\Users\zeatm\PycharmProjects\hanamii\hanami.py on line 161, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Could someone help I rlly dont know what error this is
{admin.mention}\n\n➥<@!{656938345716383777}>\n\n➥<@!{906350757169733722}>\n\n➥<@!{386879253494366208}>
It is this one
send the code
@silk mauve not related to discord bots
wdym?
what is even that
Its a moderation team command of a server
It pings the role
And then the user
like it mentions it
okay
it cant ping
okay
SyntaxError: Non-UTF-8 code starting with '\xe2' in file C:\Users\zeatm\PycharmProjects\hanamii\hanami.py on line 161, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
this
send your code
whole code?
no just the part where its throwing an error
{admin.mention}\n\n➥<@!{656938345716383777}>\n\n➥<@!{906350757169733722}>\n\n➥<@!{386879253494366208}>
thats not code lol
it is
your error isnt related to discord bots at all
mhm
I fixed it
H
!ot
async def get_pre(bot, message) -> str:
"""
i've got some questions, first of all whats bot ? and when is it getting passed same thing with message
and how would i pass the server id inside of the function arguements
and lastly whats even message
"""
return "guild prefix"
My fault havent used that attr in while
Read the docs
!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.
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
Can I update my bot’s code without restarting my bot..?
No
Why
That wasn’t the answer I was looking for
try running this and edit it to stop it
while True:
print("lol")
This maybe
That is right
Okay, Now I understand
Cool
It’s 3:47pm

learn totorals