#discord-bots
1 messages ยท Page 739 of 1
are you creating some kind of menu?
!pypi disnake
yes
well, what else would you use option 8 for?
when you use option 8 as an argument, a menu pops up
thats just how it works
but, ill give more context
idk, never seen it, I guess you're using a specific library
how to make bot prefix
ever used commands?
im tryna troll my server but my code aint workin
idk
@client.command()
async def fga(ctx):
guild = ctx.guild
users = ctx.guild.members
for user in users:
while True:
try:
await user.send("poo1")
print("Message sent to: " + user.name)
except:
print("Couldn't send to: " + user.name)
it spams only 1 person
i havent used python
...
that's against ToS and will get you ratelimited in no-time
you should learn the basics first to understand it better
ok well il change while true to make it 5 times
I'm using pycharm
i switched to vscode from pycharm yesterday
what am I with this info?
I don't see why that matters
what would you advise me to use?
Can't say, I'm not using slash commands, you'd have to ask someone who does and has done research about it
how to fix that
i changed the while true
so it doesnt spam
since its against tos
any way i can make a python code choose a random string out of a list?
im using it for a bot
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
random.choices
ah
Who is it spamming?
instead of while true, cant it be for _ in range(5)?
a bot
Hmm?
no everyone in my server
a troll but its only gonna send a msgg 5 times
and ill say bot got hacked
๐๐๐๐
import random
from discord.ext import commands
print(discord.__version__)
client = commands.Bot(command_prefix="or!")
TOKEN = "token in here"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.command()
async def ping(ctx):
await ctx.channel.send(f"In milliseconds: {round(client.latency * 1000)}")
@client.command()
async def dice(ctx):
await ctx.channel.send(f"Here is your number: {random.randrange(1, 6)}")
client.run(TOKEN)
the commands don't seem to work
nvm
i figured out whats wrong
no need for channel when sending a msg btw
and use a f string on ready
What's the error?
It shouldn't be giving one
Unless you're doing something like f"{0.user.client}"
Can someone help with Discord bots?
yes
thats what the channel is meant for :V
I need someone to build it for me - Mass invite bot looks great but really want to be careful so it doesn't spam people. I'd like to target specific server groups but have it drip feed.
That's against tos
Oh wow! Didn't know that - I'm constantly being slammed by what i believe are bots so thought that was just normal in Discord
does anyone know how to get client references from an extension?
I have a ping command I want to put in an extension but it needs Client.latency()
What is a good bot to use to grow a channel?
self.client
oh ty
I think I might be doing something wrong but it's not working
be consistent on uploading and work hard thats how you grow a channel
well, check out some Cog examples, they all have the same in common: an __init__ where client gets defined
oh so I have to turn it into a cog?
sure, it's for the better
Yes and no really - so many NFT channels and various other channels go from zero to 100k+ within a month with very little posting. This is what led us to think they are using some sort of bot
just use ctx.bot.latency if its a command
cool thanks
yeah, using ctx to get the bot object is also perfectly possible
yeah that works
None
thanks again everyone!
really depends on what the channel is for
Yeah very true! Our main goal right now is to get more people in so we can create a dialog between our group memebers. Also to build traffic to our website and NFT raffles.
ig post your nfts in a site and set your discord server and channel in the description or somewhere and make a role so if someone wants updates for nfts of you they get sent dms
how do i get a persons user
username when he / she does the command
like !hi
in terminal it would say
ctx.author
yw
you send the dm to the author
ah then use a member arg
yup i did
member: discord.Member
with a kwarg
no wouldnt work like that
await member.send(msgkwarg)
thanks
async def command(ctx , member : discord.Member):
# now you can use any property/method `member` has
# .send() method is used to send a message
ez
yup thanks aswell
you forgot the msgkwarg
he wants to send a msg to a member
didnt know that they wanted to take a message arg too , well it clears the point of "sending the message"
!sendtomember something
and it dms the member that msg
so
i have a suggestion reason here
how do i put that
into this
like i want the reason to be displayed in there
actually that might be too complicated
idk
im thinking what to write
@green bluff example of it
@client.command()
async def command(ctx, member: discord.Member = None, *, msg="empty") -> typing.Optional[discord.Message]:
if not member:
return("need to add a member")
await member.send(msg)
Is there something built in to check my bots uptime or would I have to do it myself with a bot var?
i dont understand the code
just a simple example
dont get it tho im bad at this
So lets say I use the command
!command @Water_Gazes#2352 Wow, you're looking particularly spicy today.
The @Water_Gazes#2352 part will be assigned to member which gets type hinted in to a member object
@client.command()
async def toggleDM(ctx, status):
author_id = ctx.author.id
if status == "enable":
client.noDM_list.remove(author_id)
await ctx.reply("You can now recieve dm's from me.")
elif status == "disable":
client.noDM_list.append(author_id)
await ctx.reply("You can no longer recieve dm's from me.")
else:
await ctx.reply("Please put either `disable` or `enable`")
is my code.
I have 2 questions
-
Is it possible to store the information in like a text document, or like a spreadsheet instead of a list
-
if so, how?
You would use a database
since the lists content will be removed on restart
but use the async instance
^
!pypi aiosqlite
thats why i was asking
look up lol
And you got your answer! I would suggest you check out #databases pins for guides and tutorials on how to get started but if you want a more direct link, here you go https://sqlbolt.com/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
kk ty
Its an interactive website for learning sql
I personally learnt it in 2-3 days but everyone will be different
im too impacient for that
i havent finished it ive been watching 1hour worth of memes smh
I didn't even finish it
ill speedrun it tomorrow lol
happens 
For a discord bot you don't really need to go through the entire thing
yeah
I've already made custom commands with my "limited knowledge"
you just have to know how to add and pull data mostly
Yeah
Really all you need to know is SELECT, the WHERE clause (and the operators), INSERT INTO, REPLACE INTO and maybe a bit about creating tables
and DISTINCT
Never heard of it
and FROM ofc
#databases I guess? xd
it gets unique columns only and not duplicates
true
Can I have an example where this would be useful?
@final iron im only on lesson 2 and my brain already wants to quit lol
SELECT DISTINCT author FROM movies;
only gets authors with no duplicates
if a movie has the same author it will not get it if theyres already a movie with it
In what situations have you used that?
none i havent use a db yet๐
but it is helpful
I don't see a use case for me (yet)
All I've made with my db is pp commands (funny haha), custom prefix and custom commands
Also my error handler
I log unhandled errors in to my database so I can view them later
bruhhh i cant get passed lesson 2
Which one is that?
@final iron
SELECT DISTINCT author FROM movies;
table looks like
# movie table
author: movies
john : coolmovie1
john : coolmovie2
bob : coolmovie3
will only show
author
john
bob
SQL Lesson 2: Queries with constraints (Pt. 1)
its just like an if statement in this case its called WHERE
my head hurts too much so im going back to what helps me the most. youtube
so ima be afk while i watch a yt video about it
goodluck with that๐ถ
Oh yeah, also blacklist system
And suggestion system
@commands.Cog.listener('on_member_join')
@commands.is_owner()
async def blacklist_dm_check(self, member: disnake.Member):
What was I smoking when I made this
๐ถ
How would I see how many commands I have?
most people now using nextcord or discord.py ?
I would assume there is something that returns all the commands in a list?
disnake
hm
disnake here mostly
ok thanks
Use len on commands.Bot.commands
!d disnake.ext.commands.Bot.commands
property commands: Set[disnake.ext.commands.core.Command[disnake.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
thats cool never knew
56 commands so far
Its getting up there
Still haven't subclassed my help command kekw
imagine
me with a command named help: ๐
liar
wut
Hmm?
I also use disnake 
is it different ๐คจ
120
oh shit
how the heck you know that
Thats a lot
Because I literally recoded my websocket handler for gateway
๐งโโ๏ธ
A lot until you factor all the internal calls your client does
I'll just change it every 30 seconds
You're just gonna waste bandwith by doing that
Do you really need it to update every 30 seconds
Once per minute is enough
Can I have the docs on changing your status?
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientโs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
Thanks
!d how to hack discord
#bot-commands
Do keep in mind, when sending change presence payloads to the websocket your bot will NOT receive any other events from the gateway until the presence is finished sending
So you would be blocking your bot from events 1 every 60 mins for x seconds
So maybe a bit higher than 1 minute
Probably sounds dumb, but how would cycle through different statuses?
use random.choice and pick the status from there
okimi can u help with mine
im not sure if it would work tbh
when the command is invoked check if the user has a role and if not return if yes continue the command or make a whitelist
thats a good way yes
wait i think you dont understand
i think i do
give a role that is used as a whitelist for the command
!e ```py
foo = [i for i in range(20)]
bar = iter(foo)
print(next(bar))
print(next(bar))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
did discord add buttons already?
people with that role
check if the user has the role
how would i do that
not sure what iter or next does lol
use the @commands.has_role() decorator
i think thats the decorator im not sure
and the role would be in quotation i assume
yes
yup lemme give it a try
!d disnake.ext.commands.has_role
@disnake.ext.commands.has_role(item)```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.MissingRole "disnake.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.MissingRole "disnake.ext.commands.MissingRole") or [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure")
no
and if its true
no
okay what do i do
A check() that is added that checks if the member invoking the command has the role specified via the name or ID specified.
@commands.has_role("rolename")
or use the id
no
if the check failed it will not continue
and if they do have it, it will continue
but then i have like a 20 roles in my serber
do i have to list every single role
in that check
is there like a does.not.have_role
ig check if the author has the role and if they do return a msg and if they dont it will continue
for role in ctx.author.roles:
if role.name == "rolename":
return await ctx.send("cannot use this command")
#keep doing stuff
im not sure if this would work idk
commands.has_role is a built in check which checks if the command user has the role name you gave, if they don't then it will stop right their and not continue with the rest of the command and if they do then it will continue.
tl;dr : no u cant
put it in a coro?
who's gonna put it inside a function lol
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
look at your command on the top
or whatever you have on the top
which will cause an error there
hello. I have a cog but it keeps saying that commands in it cannot be found when the commands are invoked
show the cog
!paste
- is it loaded properly?
- make sure there isn't that common indent problem and the commands are actually inside the subclass
dont get it
it wasn't for u
@spring flax your missing self
@commands.command()
#@commands.check_any(commands.is_owner(), commands.has_role())
async def edit(rule, ctx, message : disnake.Message, *,new_content : str):
if not message.embeds:
await message.edit(content=new_content)
else:
embed = message.embeds[0]
embed.description = new_content
await message.edit(embed=embed)
and setup should not be in the class
@slate swan
damn okimii faster
I'm light
check whatever you have on the top its giving a error
...
to literal
?
i ment what you have on the top of that command thats giving the error
nice
gonna check if it works
did you loaded the cog?
Same error? And does only this cog not work?
well, oops
@slate swan it says i suggested the command but it also says i cant use it

the for loop i gaved is to check if the author has a black listing role
You could use discord.utils.find method in here
never used utils๐ถ
haven't seen you in a while
i dont know what u mean
They are useful
would thios work
!d discord.utils.find
ยฏ_(ใ)_/ยฏ
discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is โMightyโ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
tryitandsee
i meant to say ** I tried it and it definitely doesnt wokr**
Error?
Hmm did you pass the reason?
@commands.cooldown(1, 600, commands.BucketType.user)
async def suggest(ctx, *, reason=None):
if reason is None:
await ctx.reply("Please enter a suggestion.")
else:
for role in ctx.author.roles:
if role.name == "suggest":
return await ctx.send("cannot use this command")
else:
embed = discord.Embed(title="",
description=f"**Suggestion** : {reason}",
colour=discord.Colour.orange())
embed.set_author(name=f'{ctx.author}s Suggestion.', icon_url=ctx.author.avatar_url)
channel = client.get_channel(928950254798258196)
await ctx.channel.purge(limit=1)
await channel.send(embed=embed)
embed = discord.Embed(title="**Suggestion sent!**: ",
description=f"**{reason}** | You will be dmed once a decision is made.",
colour=0xFFFFFF)
await ctx.author.send(embed=embed)```
and are you the server administrator?
ye
I want it to cycle though
This would actually loop for every role that doesnt have the name "suggest
a task loop lol
You should use command checks instead
show us the role name
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
also it's a bad method to loop through author.roles and look for it
whats tha
simply use utils.get()
I am. If I use random.choice there's a possibility it will land on the same one
did you mean cycle by this? @final iron
command checks are special decorators that check for a condition before the command starts
please give me the code i dont get where u want me to put utils.get
im new to all this
you can use itertools.cycle
just tell me then
wdym where to put utils.get
Can I get an example?
wdym where???
Yes
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
from itertools import cycle
statusesโย โ=โย โcycleโ(["...", "..."]) # statuses here
@โtasksโ.โloopโ(โminutesโ=โ12โ)
asyncโย โdefโย โstatus_changeโ():
โย ย ย ย ย ย ย ย โawaitโย โbotโ.โwait_until_readyโ()
โย ย ย ย ย ย ย ย โawaitโย โbotโ.โchange_presenceโ(โactivityโ=โdiscordโ.โGameโ(โnextโ(โstatusesโ)))
Thanks my guy
Remove the else statement
Np
This is another prime example of why you should learn python before jumping in to a discord bot
OH WAIT IK
!d discord.Guild.roles
property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guildโs roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
or have a black listing role as i said
like that iirc
it doesnt remove the role tho
can your bot remove roles?
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
and is the bot role higher than the one you will remove?
i changed it just now lemme try again
no it doesnt remove his role no errors either
@client.command()
async def approve(ctx, member: discord.Member):
role = discord.utils.get(ctx.guild.roles, name='suggest')
embed=discord.Embed(title=f'Your suggestion has been approved by **{ctx.author}!**', description='Thank you for helping build our community!', colour=0x00FF00)
await member.send(embed=embed)
await ctx.author.remove_roles(role)
your trying to remove the role from yourself btw
lol
im the author
yes
Can you pass in a list to utils.get()?
Because that's what he's doing
never used utils
Me neither
lol
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
You can
ic
Should I make an economy system?
I'm kinda on the fence
I don't see a reason to make an economy system when dank memer has a monopoly but I feel it would be fun
sure but make it a international system which can take all currencies
you can store any type of currencies and you can make transactions with the money (buy ranks/roles) and can make converters that converts the currencies to other currencies
idk maybe for clubs or clans or shops that you can buy special stuff from them only
Rpg game when?
good idea
Would anyone know how to make a bot play an audio file in a channel.i can make the bot join and play but then I have to get it to leave and rejoin.
I'll just start with basic economy shit
Deposit, Rob, hunt, job and all that jazz
Being creative is going to be hard
Wrong server
๐
Wait you were actually in the wrong sever lmao
wait what?
๐ถโโ๏ธ any bot name ideas?
whats the bot for?
currently nothing , im just making it for use in some private servers
Why though
why not
how about i name it ramen
Why not
no
with a ramen avatar
name it ganbare
๐ณ
nice idea ๐ณ
๐
If my bot gets bigger I'll contact someone to make my own
Same
yeah
i have rias in the pfp of my personal private bot๐ณ
My server makes fan art for it anyways ๐
i hab kakashi
no
๐
make a command that gives command ideas๐ง
Or else...
Suggest more topics here!
LMAO
I have a cogs, I'm trying to load them by using ```py
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'{filename[:-3]}')
but it keeps saying extension 'test' has no setup function, (test.py is the cog name)
it does not have a set function as the error says
doesnt it speak for itself?
you probably made it inside the cog class lol
it's outside
let me send it here one second
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
You need to add
def setup(bot):
bot.add_cog(YourCogClass(bot))
at the end of each cog.
he clearly has it
def setup(bot):
bot.add_cog(Test(bot))
No init function
i did that, outside the class
It's
def __init__
and not
def init
bruh def init ๐ญ
thats a magic method/dunder ๐ญ
it still raises the error
do cogs need to be in a folder or can they be in the same folder as the main code just another file?
you have a for loop right?
i mean right now i just have one cog
so it will loop through all the files in that directory which end with .py so in that case yes they should be in a separate folder so you wont load you main file or other files
i can't just load a cog like bot.load_extension('test') ?
yes you can if you have one yes
and if i were to do that, does the one cog have to be in a folder?
or can i just create a new file
no your just loading that cog?
!d discord.ext.commands.Bot.load_extension
load_extension(name, *, package=None)```
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
welp im going to go to sleep Gn guys
im trying to set up my discord bot to read how many players are online in one of my gaming servers any ideas?
@client.event
async def on_member_leave(member):
channel = discord.utils.get(member.guild.channels, id=733201139478036501)
embed=discord.Embed(title=f"Goodbye,{member.name}.", description=f"{member.name} has left {member.guild.name}.")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)
await member.send(embed=embed)
What's wrong with this? It does not do what its supposed to do.
Well, what does it do ๐คท
Its supposed to send an embedded message to a specific channel when someone leaves the server.
It is not doing anything, no errors.
Have you enabled the Members Privileged Intent in the developer portal and in your code?
yes
May you show?
sure
Just to make sure ^^
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(command_prefix = 'v!', case_insensitive=True, intents=intents)
this is what's in my code
It's case_insensitive just as side note.
please
The event is not called on_member_leave
!d discord.on_member_remove
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Well try it now at least.
sure
on_member_leave will never work as it doesn't exist.
should add it to a try and except
because your trying to dm a member that left a guild and if that member doesnt have mutual guilds with the bot it wouldnt dm the member afaik
Did not work.
I am new to discord.py could you tell me how please
not really something about dpy but more py
Personal opinion, discord.py feels like something entirely different than python to me xD
i mean its not really maybe the fact that it uses oop and async programming is what makes you feel that way
It's a Python library, so there's nothing different to Python when you're using discord.py :)
typehints that convert stuff to objs
A try/except should be nothing new to you.
it isn't
I did it, I am removing the bot from the host atm
Updating it is too long
of a process
@client.event
async def on_member_remove(member):
try:
channel = discord.utils.get(member.guild.channels, id=733201139478036501)
embed=discord.Embed(title=f"Goodbye,{member.name}.", description=f"{member.name} has left {member.guild.name}.")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)
await member.send(embed=embed)
except:
print("Did not work")
finally:
pass
The output was Did not work
print the error if any
then it wont dm the user
but wait
it actually worked
but still the output at the terminal was Did not work
huh
if that member doesnt have mutual guilds with the bot it wouldnt dm the member afaik
Yea I got that I just did not remove it
weird
If the member is still in bot's cache ( as a user ) it will
^^^
yes
good to know
im playing around with dis-snek and added slash commands, when trying to use it though, the menu is freaking out. anyone ever seen something like this and has any idea?
maybe your discord client is bugging out im not sure
nah i let another guy test it and he has the same
i can "fix" it by kicking the bot and reinviting it, but every new command i add is causing this again
thats weird never seen it happen before
I want the owner of the server to have a command that allows him to set a on_member_join role. How do I do it?
elaborate
Let me tell you how it will work,
v!set_member_join_role <role here>
so now whenever someone joins the server they get this role automatically.
for a command check like
def something():
def predicate(ctx):
for the parts where it lets them use the command, i should write return True, and for the parts where it should not let the user use the command it's return False right
you can use a var and change the value of it to the name of the role or use a db
I have tried that, But how do I use the same var in the on_member_join event?
@client.command()
async def set_on_join_role(ctx, role : discord.Role):
role_ = discord.utils.get(ctx.guild.get_role(role))
return role_
I guess this is what you meant by that
I guess it has something to do with decorators?
yeah
@client.event
async def on_member_join(member):
channel = client.get_channel(733201137615765616)
embed=discord.Embed(title=f"Welcome {member.name}.", description=f"Thanks for joining {member.guild.name}!")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)
await member.send(embed=embed)
await member.add_roles(member.guild.get_role(854387380278919238))
``` I simply can't think of a connection between that command and this event.
how to keep your bot online forever
await member.add_roles(member.guild.get_role(854387380278919238))
``` Here I want the id given here to be the role I just returned in the given command.
vps
host it, heroku
no
heroku works just fine for me
add the function you just showed
what
it returns a role doesnt it
idk what u saying
Yeah, How? Decorate it?
Still don't get how it will help in any way.
await member.add_roles(member.guild.get_role(set_on_join_role()))
``` You mean this?
how does discord dev api work, why doesn't it need open ports
!e
def function() -> str:
return "hello world"
print(function())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello world
the function returns a value which in this case its a str
Its just that I want to confirm everything before I do. If I mess things up that will be a BIG mistake
So this should work
yeah
role_ = discord.utils.get(ctx.guild.get_role(role))
retuned error
TypeError: 'NoneType' object is not iterable
role is none
I'll try using converter
hm was @unkempt canyon made with dpy
no, dpy was made with python
@unkempt canyon bot
!bot
Bot informational commands.
dude
not the lang
Ohhh
!bot
!bot
Bot informational commands.
!source
As you can see, yes.
there's nothing wrong with this code right?
def permission_check():
def predicate(ctx):
if (discord.utils.find(lambda r: r.id == 873148465956417576, ctx.author.roles)) and ctx.channel.id == 929989647046696990:
return True
else:
return None
return commands.check(predicate)
Uhm what are you trying to do here
doesn't return None raise the missing permission check failure?
My bot suddenly stopped working and i have no idea why
I didnt change anything and it just suddenly says error
Let it rest for a bit maybe it's temporary server error
I dont know what this means
@strong vessel
Oh it's blocking ip
Wherever your server is hosted is getting blocked by discord due to heavy traffic
Itโs replโฆ
How the hell
probably someone else is doing it
Probably some spammer using repl
oh
yeah
Ok so should I transfer code to another repl?
does that change the ip?
If you don't mind it you could try waiting it out
Lemme try anyways atleast i know whats the problem now thanks
So basically someone hacked my repl?
no
Or is spamming traffic on it?
repl shares ips
No someone else using repl is spamming discord
the api
nope
your fault is using replit
Stolen token i guess
๐ญ
๐
OH SHIT
no
No just relax
no
no
Ok
replit shares ip smh
is there any simple module to implement nlp for my bot?
i dont wanna risk anything
Use heroku
Yep its hosting
Itโs blocking my ip rn
Just regenerate if that's the case..
I got hacker plan for free
not the case smh
use ovpn
have you guys read my msg and others msgs?
Ok will do

I use heroku
Idk what to do at this point except waiting

or use uprobot
It doesnt let me turn on my bot
hurts doesnt it
๐ถ
alot
me rn:
๐ช ๐ถ
Can anyone explain in brief what cogs are?

just extensions for commands and events
am i missing something ?
no
Does anyone know the correct syntax to send a message in chat with a matched phrase? My code doesn't recognize when I use the word in a sentence.
how to grant roles to members
eg for 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.
wdym by that
When I was coding the bot, it would only respond to the word if it was not in a sentence. I wasn't using the split method. So, that part is okay now. But now the bot will not ignore itself and spams the channel.
why isn't my bot getting ratelimited?
sends around 50 messages / minute
on 100 servers
50*100 = too fucking much
because the lib handles ratelimits for you
huh
I mean it just keeps sending bro it aint gettin ratelimited
dont write
just by seeing ur name
dont write anything
i know and it wont because the lib handles it
?
if not message.author == bot.user:
#do stuff```
if not message.author.bot:
Will ignore all bots which is much better and not just the bot itself
7-zip
is there like a one line code that removes roles that have send_messages permissions? if so, could you please share it with me? (discord.py)
Hello
in a one liner , why would you do that
i play scum and im trying to get my discord bot to read how many players are currently online, any help?
in your server?
yeah
for my mute code, when it adds the mute role, it removes roles that have send_messages permissions because then the role would be useless.
iterate thru Guild.members and check if Member.status is online , idle or dnd
you can loop through all the roles on the user using member.roles and remove the role if it has send_messages perms
Role.permissions.send_messages would be true if member has the perms
how to turn discord ID to username#1234 if the user is not in ur server?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
get the user . and use str(user)
I've got an idea that I would like to share with you guys :)
Imagine, a Discord bot that simulates an economy system, based off of real life economy. A bot that let's you create shops, sell items to other users, plant your own virtual crops in Discord. Basically, a bot that simulates real life to some extent in Discord (think of it as a type of roleplay)!
What do you think?
so do I do this through the battlemetrics site or would i do it through my servers ip?
would be great
and will also be a lot of work
How to get the url of a mp4 file
too much work. if i had a team of okay developers i would go for it, and time of course
wait , you want to get the members online in your discord server right?
how is that related to a game
I'm currently coding such a bot, it's very limited at the moment and there's not much to it.
!d discord.Attachment.url
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
so im an admin of my own scum server. which is a game. id like to make a discord bot that shows my discord server how many players are currently in the game.
what's your plan further , like collabs or something?
And how to take an attachment as input?
Would you guys like to check it out? I can create a server with the bot in it.
you can check if Member.activity is the game
The name of the activity.
im super new to this so im sorry if im not explaining right.
feel free to dm me the link
so ill assume you want to check how many members in your server are playing a game named scum , right?
Yess me please
sure i would contribute
no. because they play on multiple servers. id like to show how many players are on the game server i own, on discord.
scum has something like a game server?
yeah scum has multiple servers. you can rent your own
idk if youve played rust but you can use a bot on rust to show how many people are currently in your rust server. id like to do that with my scum server.
You might want to check out something like this: https://api.rust-servers.info/
yes! so battlemetrics has an api ive looked through but im not exactly sure how to read it all
It's simple JSON reading.
Here are some links for reading that data:
https://stackoverflow.com/questions/7750557/how-do-i-get-json-data-from-restful-service-using-python
https://www.nylas.com/blog/use-python-requests-module-rest-apis/
thank you so much
.topic
Suggest more topics here!
how to use dis
See their API documentation: https://www.battlemetrics.com/developers/documentation
We don't know since you coded, most likely copied, it.
wht
this is so hard XD
You need to define the open_account function.
oh ok
not true
So continue the tutorial you're following, then it will be done ^^
It's different for everyone :)
I mean it might be hard for them, but the language isn't hard
yeah i feel like its simple im just making it super hard. ive never taken any kind of coding and just kinda jumped into this today
'this' โ hard
So you never learned to code?
cant learn something in 1 day bro
wait, so it isn't built-in system?
No.
As I said:
So continue the tutorial you're following, then it will be done ^^
nah lol. butttt i did get my bot to say hello back to me lol
then how to make my bot dm'd me when vote
I need help coding a command, idk how to code it but i have the idea in my head
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
tbh I have no idea when I learnt python, I just kinda learnt it somehow
he just add await open_account(user) done
As I said, continue the tutorial.
done
Im trying to code a custom command
I might be asking for too much so nvm
The message above is the way to code a help command.
@bot.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
if member == ctx.author:
em = discord.Embed(
description=f"**you** cannot `mute` yourself", colour=discord.Colour.red()
)
await ctx.send(embed=em)
else:
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
role = discord.utils.get(ctx.guild, name='๐ผ | owner', '๐ฎ | co-owner', '๐ฅ | moderator', '๐ฎ | rich', '๐ค | streamer','๐งผ | personal assistant', '๐ | girls', '๐ | boys')
await user.remove_roles(role)
em1 = discord.Embed(
description=f"{member.mention} has been `muted` for **{reason}**",
colour=discord.Colour.green(),
)
em2 = discord.Embed(
description=f"**you** have been `muted` for **{reason}**", colour=0
)
await ctx.send(embed=em1)
await member.send(embed=em2)
list_of_muted_members.append(member)
print(list_of_muted_members)```
theres an error, could anyone help?
kek
role = discord.utils.get(ctx.guild, name=':blossom: | owner', ':crystal_ball: | co-owner', ':fire: | moderator', ':cow: | rich', ':robot: | streamer',':soap: | personal assistant', ':ribbon: | girls', ':gem: | boys')
^
SyntaxError: positional argument follows keyword argument```
because you cant do that?
role = discord.utils.get(ctx.guild, name='๐ผ | owner', '๐ฎ | co-owner', '๐ฅ | moderator', '๐ฎ | rich', '๐ค | streamer','๐งผ | personal assistant', '๐ | girls', '๐ | boys')
await user.remove_roles(role)
This will never work
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
You can't remove roles like that as you wish.
oh, how can i?
you can do await user.remove_roles(Role1, Role2, Role3) but nto role = discord.utils.get(ctx.guild, name=':blossom: | owner', ':crystal_ball: | co-owner', ':fire: | moderator', ':cow: | rich', ':robot: | streamer',':soap: | personal assistant', ':ribbon: | girls', ':gem: | boys')
oh god
done, and no further explanation about that, just await open_account(user)
also why pay for winrar
So if you blindly follow a tutorial without knowing what the code does or anything similar, then at least entirely follow the tutorial.
or dont follow it
๐คทโโ๏ธ
i think you should do some basic python things first and then code the bot
then at least entirely follow the tutorial.
atleast if the tutorial is spoon feeding
does this server do any kind of on hands help?
that what i do :l
dont jump into doing it immediately
Such as?
No you're not doing it.
english = basic python
literally
the syntax is just english
You directly stopped after you got that error, so continue the tutorial and look at previous videos of the series.
I want to make a command, so if I do .verify @near osprey, itll give the person the community role
@bot.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
if member == ctx.author:
em = discord.Embed(
description=f"you cannot mute yourself", colour=discord.Colour.red()
)
await ctx.send(embed=em)
else:
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
role = discord.utils.get(ctx.guild, name='๐ผ | owner', '๐ฎ | co-owner', '๐ฅ | moderator', '๐ฎ | rich', '๐ค | streamer','๐งผ | personal assistant', '๐ | girls', '๐ | boys')
await user.remove_roles(role)
em1 = discord.Embed(
description=f"{member.mention} has been `muted` for **{reason}**",
colour=discord.Colour.green(),
)
em2 = discord.Embed(
description=f"**you** have been `muted` for **{reason}**", colour=0
)
await ctx.send(embed=em1)
await member.send(embed=em2)
list_of_muted_members.append(member)
print(list_of_muted_members)
i feel like im not going to code or use python much after this. so i was wondering if this server has somewhere that will just show me how to do this.
All we can say is, follow the entire tutorial. We can't help further.
We don't code for you, we help you face your issues and guide you.
?
fair enough
wtf happened to this 
It doesn't exist.
what doesn't exist?
I want to make a command, so if I do .verify @example, itll give the person the community role
the PartialMessageable thing you tried to import
What is being imported, discord.channel.PartialMessageable
why tho?
i didn't import that trash?
Not you, the outdated library you're using imports it :p
so what should i do?
File "main.py", line 192
await user.remove_roles(:blossom: | owner, :crystal_ball: | co-owner, :fire: | moderator, :cow: | rich, :robot: | streamer, :soap: | personal assistant, :ribbon: | girls, :gem: | boys, )
^
SyntaxError: invalid character in identifier```
so what works?
x = ...get_role(role_id)
x1 = ...get_role(role_id)
...
await member.remove_roles(x, x1)
so for example, the "x" and "x1" is the role name?
No.
It's a variable..
You need to get roles based on their ID, not name.
You can't just do
await member.remove_roles("name 1", "name 2")
They need to be Role objects.
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
And get_role gives you a role object back.
!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.
How to make it so if someone does .verify @1234, the person mentioned is given a role
@slate swan
Add a parameter in your command and type hint it to discord.Member.
Then you can use get_role(role_id) and assign it to a variable.
Then you can use add_roles(var) to give the member the role.
x = ...get_role(883538063496708116)
^
SyntaxError: invalid syntax```
just make it a command and give the ctx.author the role
oh.
dont copy paste code without knowing/understanding what it does
use discord.utils
wdym
from discord.utils import get
role_id = 123
role = get(guild.roles, id=role_id)```
you could do that, altho i dont suggest it since its overwriting some python namespace
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
check this out
My code is an example on how to use, not to copy paste.
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Replace ... in ....get_role(883538063496708116) with a Guild object. Something like message.guild or ctx.guild, depending on where you have the code.
is it possible to embed a video into an embed
No.
ok
Hey uhh I am new to discord.py and I need to build a bot that deletes a channel if the channel name starts with something, is that possible? I think that's theoritically possible but I have no idea how to even code it
Yes it is.
hey can you help me
When do you want to do that? Upon channel creation or using a command?
Upon using a command
Then you need to loop through all the channels in the guild -> guild.channels.
And check if the channel.name starts with what you want, then you can use channel.delete() to delete it.
import discord
from discord.ext import commands
from pokemontcgsdk import Card
from pokemontcgsdk import RestClient
bot = commands.bot('&')
if os.path.isfile('.env'):
load_dotenv('.env')
else:
pass
RestClient.configure(os.environ['api_token'])
token = os.environ['token']
@bot.command(name="ptcg", brief="pokemon tcg card finder", description="Finds the card that matches the id \nex** xy1-1")
async def ptcg(ctx: commands.Context, id):
card = Card.find(id)
embed = discord.Embed(colour=0x03fcad,
title=f"{card.name} {card.nationalPokedexNumbers}",
description=f"type: {card.types}\nweakness: {card.weaknesses}")
embed.set_image(url=card.image.large)
embed.add_field(name="Moves [for now only 1 is dsiplayed]",
value=f"{card.attacks.Attack.name} | {card.attacks.Attack.text} | {card.attacks.Attack.cost} | {card.attacks.Attack.damage}")
embed.add_field(name="Other Info",
value=f"series: {card.series}\nrarity: {card.rarity}\nRelease Date: {card.releaseDate}")
await ctx.send(embed=embed)
bot.run(token)```
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
Upon using a command
what's worng with this code
It's commands.Bot not commands.bot.
And you need to pass command_prefix="&"
ok other then that
ok I fixed that
but the embed is not showing when I type &pktcg xy1-1 @slate swan
can we use a for loop like for i in range(guild.channels) or something?
Just for x in guild.channels :)
Can you tell why the code isn't working even though I fixed the mistake @slate swan
ahh i see i forgot, i need to call i to remove it again 
Why would I need to do that when you already fixed it :p
I won't waste my time at looking at it if you already fixed it..
the code isn't working
then its not fixed
even though I did what you told me too
from nextcord import colour, embeds
from nextcord.ui import view
import nextcord
from nextcord.ext import commands
class Button(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label='1',
style=nextcord.ButtonStyle.green,
custom_id="first")
async def first_button(self, button: nextcord.ui.Button, interaction : nextcord.Interaction):
print("first button click")
@nextcord.ui.button(
label ="2",
style=nextcord.ButtonStyle.secondary,
custom_id="second")
async def second_button(self , button : nextcord.ui.Button, interaction: nextcord.Interaction):
print("second button click")
class Test(commands.Cog):
def __init__(self, bot: commands.AutoShardedBot):
self.bot = bot
@commands.command()
async def testb(self,ctx):
await ctx.send("test", view = Button())
def setup(bot: commands.Bot):
bot.add_cog(Test(bot))```
how do I make te 2nd button below the 1st one instead of being beside it ?
I have did it in discord-components but have no idea how to do in nextcord
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
if message.content == 'clean':
async def complete(ctx):
guild = None # grab all guild from server that match
id_admin = discord.Role.id = None
overwrites = {
id_admin: discord.PermissionOverwrite(send_messages=True),
guild.me: discord.PermissionOverwrite(read_messages=True),
}
for i in guild.channels:
if i.channel.name.startswith(''):
await i.delete()
client = MyClient()
client.run('')```
I got this far only, please help ;-;
Sending your message again won't change anything.
I deleted my orevious one because there was a mistake
And as I said it's just channel.delete()
a bad one
ah alr
!d nextcord.ui.button
nextcord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`nextcord.ui.View`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.View "nextcord.ui.View"), the [`nextcord.ui.Button`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.Button "nextcord.ui.Button") being pressed and the [`nextcord.Interaction`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction "nextcord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.Button "nextcord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.