#discord-bots
1 messages · Page 504 of 1
you know the cooldown error you get when a command is on cooldown??? i want to have limit to how many times that error can go off because i dont want people to be able to spam a command and get my bot rate limited i.e. i spam .command 20 times and it says command is on cooldown 20 times i need it to only say it twice
i would but it's 1 am and i gonna go between now and 1 second.
Get some rest sweet panda person
subclass asyncio.Lock and sleep before the release call and ypu could have a mapping of author id and lock
!d asyncio.Lock
class asyncio.Lock```
Implements a mutex lock for asyncio tasks. Not thread-safe.
An asyncio lock can be used to guarantee exclusive access to a shared resource.
The preferred way to use a Lock is an [`async with`](https://docs.python.org/3.10/reference/compound_stmts.html#async-with) statement:
```py
lock = asyncio.Lock()
# ... later
async with lock:
# access shared state
```...
If you are still having issues tomorrow i could help at a normal time lol. Gl
wat?
Thank you 
subclass it, overload __aexit__ to have an asyncio.sleep
Couldn't you just use a the custom cooldown on the message?
!customcooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
I think the custom cooldown is optimum then
As you get ctx.message in on_command_error
asyncio.lock could work as well
actually I think it might be cleaner to use asyncio.lock
¯_(ツ)_/¯
so how would i use it to only send like 2 on cooldown messages then it wont react or send another message untill the cooldown is over
add the times its been said until it reaches 2
you can use that custom cooldown or use asyncio.Lock
when its at 2 just do nothing until it ends
yes
retry after is just time untill you can do it again
commands are run inside on_message which is run inside a task, if you use asyncio.sleep it would basically do nothing?
i mean null’s idea is really vague imo
so how would i do this?
uhhh
an asyncio.Lock
read what it does
it limits access to a resource
in your case, as i said before, you could have it sleep before releasing the lock
how would i implement this?
by using a subclass and a dict
just wondering
you wouldn’t want this to apply to everyone at the same time
is my regex for catching pings bad?
(@!*&*[0-9a-zA-Z]+)
i know nothing about regex tbh
why is there a-zA-Z? pings only have numbers
<(?:@(?:!|&)?|#)([0-9]{15,20})>$ is the one discord.py uses
for pings like @\here
Not for pings like here and everyone
I'm pretty sure they have another one for that not sure
import
import what?
random
thx
]
?
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
it returns a random number between two points
show code
xd
did i do smth stupid?
use commands and not on_message
i used commands
what is that
?
@hasty iron you can help
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Client._run_event' was never awaited``` Why would discord-ext-ipc be throwing this
await it?
did you classify the channel?
what channel?
you did await message.channel.send
hello
it really is dumb tbh
indefined name 'ctx'
no you gotta change the code a bit
full error? and code
import discord
from discord.ext import commands, ipc
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc = ipc.Server(self, secret_key="my_secret_key") # create our IPC Server
async def on_ready(self):
"""Called upon the READY event"""
print("Bot is ready.")
async def on_ipc_ready(self):
"""Called upon the IPC Server being ready"""
print("Ipc is ready.")
async def on_ipc_error(self, endpoint, error):
"""Called upon an error being raised within an IPC route"""
print(endpoint, "raised", error)
my_bot = MyBot(command_prefix="!", intents=discord.Intents.all())
@my_bot.ipc.route()
async def get_member_count(data):
guild = my_bot.get_guild(
data.guild_id
) # get the guild object using parsed guild_id
return guild.member_count # return the member count to the client
if __name__ == "__main__":
my_bot.ipc.start() # start the IPC Server
my_bot.run("")``` This is the code, I dont thing mybot.ipc.start needs to be awaited
File "/Users/matthewjames/Desktop/LooicDevelopmentServices/Python Testing/bot.py", line 37, in <module>
my_bot.ipc.start()
File "/Users/matthewjames/Desktop/LooicDevelopmentServices/Python Testing/venv/lib/python3.9/site-packages/discord/ext/ipc/server.py", line 253, in start
self.bot.dispatch("ipc_ready")
File "/Users/matthewjames/Desktop/LooicDevelopmentServices/Python Testing/venv/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 154, in dispatch
super().dispatch(event_name, *args, **kwargs) # type: ignore
File "/Users/matthewjames/Desktop/LooicDevelopmentServices/Python Testing/venv/lib/python3.9/site-packages/discord/client.py", line 403, in dispatch
self._schedule_event(coro, method, *args, **kwargs)
File "/Users/matthewjames/Desktop/LooicDevelopmentServices/Python Testing/venv/lib/python3.9/site-packages/discord/client.py", line 363, in _schedule_event
return asyncio.create_task(wrapped, name=f'discord.py: {event_name}')
File "/opt/homebrew/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 360, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Client._run_event' was never awaited```
works now thx
Yeah sry just realizes that
np
@hasty iron
yes i saw
well its an issue related to how discord.ext.ipc tries to dispatch before the bot is running is what i am@getting
@client.command()
@commands.check_any(commands.is_owner(), commands.has_permissions(manage_channels=True))
async def help(ctx):
embed=discord.Embed(title="Embed Bot", color=discord.Colour.random())
embed.add_field(name="\uD83E\uDDCA `"+prefix+"help`", value="Shows all commands' info", inline=False)
img = ctx.message.author.avatar_url
embed.set_thumbnail(url=img)
embed.add_field(name="\uD83E\uDDCA `"+prefix+"embed <message>`", value="Sends embeded message\n *(Requires 'Manage Channel' Permissions)*", inline=False)
embed.add_field(name="\uD83E\uDDCA `"+prefix+"about`", value="Shows info about the bot", inline=False)
embed.timestamp =datetime.datetime.utcnow()
embed.set_footer(text="Requested by {}".format(ctx.author))
await ctx.reply(embed=embed) ```
Error:
async def help(ctx):
^
Invalid Syntax```
you forgot the @
Where?
@commands.has_permissions(manage_channels=True)
But isn't in braces
and you have an extra closing parentheses right there

Lemme check
I dont understand what you wanna say,
This is working in my other command
oh, you are using commands.check
do you have anything wrong above it?
just try this but do
@client.command()
@commands.is_owner()
@commands.has_permissions(manage_channels=True)
and see if there are any errors
How do I send DM to a member through his ID ??
Yea
Uhm
I can tell you how to dm a author
Of the command
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
use that
thanks 🙂
and if that fails then use fetch_user but that makes an api call so use it with precautions
sync def help(ctx):
embed=discord.Embed(title="Embed Bot", color=discord.Colour.random())
embed.add_field(name="\uD83E\uDDCA `"+prefix+"help`", value="Shows all commands' info", inline=False)
img = ctx.message.author.avatar_url
embed.set_thumbnail(url=img)
embed.add_field(name="\uD83E\uDDCA `"+prefix+"embed <message>`", value="Sends embeded message\n *(Requires 'Manage Channel' Permissions)*", inline=False)
embed.add_field(name="\uD83E\uDDCA `"+prefix+"about`", value="Shows info about the bot", inline=False)
embed.timestamp =datetime.datetime.utcnow()
embed.set_footer(text="Requested by {}".format(ctx.author))
await ctx.reply(embed=embed) ```
Still error
?
send the code and error
What is error
did you do
@client.command()
@commands.is_owner()
@commands.has_permissions(manage_channels=True)
at the beginning?
then check if there are errors
Lemme send code
!code
ok, take your time
!code
!code
oop lmao

Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yea but it was working good yesterday
But when my bot got rate limited, I edited the code and this happened
what is discord.Colour.random
Its embed colour
Random colour
To choose a random colour of the line
<- That coloured line in embed
do discord.Colour.random() @slate swan
wait you did nm
Yea
so every command works except the help command correct?
Yes
hi guys
i've set up a bot that on command goes to a specific voice channel (specified by channel id) and plays an audio file
how would i make it go to a different voice channel if
the command was used in a specific text channel (defined by id)?
oh in the fields, you need f strings
Well I just checked in replit, that none of the command is working
I think its because of the commands.checkany
none of the commands?
bruh i thought it was only the help command lmao
Try changing line 18 to this
await client.change_presence(activity = discord.Activity(discord.ActivityTye.listening, name =f"to {prefix} in {str(len(client.guilds))} servers")
```@slate swan
Ok wait
Probably it's because of the previous lines
thats what i said
yeah
i said it in the fields cuz i thought you said only help command lmao
I mean, the bot will check that either I or a person with manage channels perms should be able to access the commands
@client.command()
@commands.is_owner()
@commands.has_permissions(manage_channels=True)
are the other commands working?
IDK testing....
ok
its possible you have an on_message event in which commands arent being processed?
do you have an on_message event anywhere?
Commands simply giving syntax error
@patent lark this is their code
okay
then if you know python then you should be able o fix them by yourself?
@slate swan did you implement f string on the client.event
Yea but I csnt find error
Yea
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@commands.has_permissions(manage_channels=True you are missing a parenthesis at the end
Still error
also do f strings in your help command as well
embed.add_field(name=f"\uD83E\uDDCA ` {prefix} help`", value="Shows all commands' info", inline=False)
img = ctx.message.author.avatar_url
embed.set_thumbnail(url=img)
embed.add_field(name=f"\uD83E\uDDCA `{prefix} embed <message>`", value="Sends embeded message\n *(Requires 'Manage Channel' Permissions)*", inline=False)
embed.add_field(name=f"\uD83E\uDDCA `{prefix} about`", value="Shows info about the bot", inline=False)
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text="Requested by {}".format(ctx.author))
like this
I am saying that I tried to remove helpbcommand
But it still give same error on other command
whats the error.
syntax i believe but let blank say the error
? how do you not know how to fix that?
I saw the code multiple times
@slate swan move the async down a line in the embed command
that clearly tells us that you dont know enough python to use discord.py
but?
maybe theres something called auto rotate in your phone?
and idk why you would code on phone
like that just does not make sense
because no pc or laptop
some people just do not have the resources to code on pc due to many reasons
Nah its 6 am here
maybe theres something called dont be rude?
ppl might not have enough money to buy a pc too
maybe theres something called common sense?
I said I have a pc but I cannot open it right now because its 6 am here
its not "common sense" to people who are new to coding?
anyways...
just open your pc
i use mine at 5 am
new? then why are they using discord.py?
why are you awake at 6 am
thats not a question for me.
then why did you say new to coding?
because its obvious
the real question is why didnt you wake up at 5 am
lol then dont say it
dont say theyre new? its obvious they're new, but it doesnt mean you have to be rude.
anyways, you can continue lmfao, i cant stop you from coding on a phone.

not everyone has the resources like other people do, sasuke, you seem to have a hard time understanding that.
Uh excuse me
Is there a tab before async def help
yes
also you can remove the @command.is_owner
there should not be a tab there
wait I AM OSO STUPID
Yea I thought that about the tab
I need it cuz in some of the servers I dont have that perms
@bot.command()
async def hello(ctx):
await ctx.send("Hello")```
basic command
Everything was working good yesterday
Bad things started when my bot got rate limited in replit and I tried to add is_owner command

try removing the help command and saving it somewhere and see if the bot works without the help command
Could anyone help me rq with this command im trying to make?
It didnt
I think there is something in @commands.is_owner and has perms
did you remove the @help.error with it as well
Yea
Its now giving error in embed command
Also I found this on stackoverflow
Cant we use something like this```py
@commands.is_owner() or @commands.has_permissions(manage_channels=True)```
@stark hearth
no
Sad
my bad for caps i was dm someone
👍
Im trying to make a command that only I can use. Everyone who uses the command gets the "You are not allowed to use this command" response, including me
async def servers(ctx):
if ctx.author.id == '298856608585351168':
await ctx.reply('Info posted in bot panel.')
print('BotName is in these servers:')
print('---------------------------')
for guild in client.guilds:
print(guild.name)
print('---------------------------')
else:
await ctx.reply('You are not allowed to use this command.')```
Could anyone help please? Thanks
You can usepy @commands.is_owner()
Isnt that the server owner?
nah
ohhh really?
Just add your owner_id inpy client=bot.Commands(owner_id=Your ID)
thats pretty cool, thank you :)
:)
you dont need to do that
no its the bot owner
perfect, thank you all
theres no need to add the owner_id kwarg in commands.Bot() to use @commands.is_owner()
true
ok bye bye
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
also?
i need help, how can make the roles not position like this
go do your exams
Give them more room
how?
@commands.command(aliases=["whois"])
async def userinfo(self, ctx, member: discord.Member = None):
if member == None:
member = ctx.author
roles = [role for role in member.roles][1:]
embed = discord.Embed(
description = f'**User Infomation - **{member.mention}',
colour=member.color,
timestamp=ctx.message.created_at
)
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(text=f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)
embed.add_field(name='ID:', value=f'`{member.id}`')
embed.add_field(name='Nickname:', value=member.display_name)
embed.add_field(name='Created at:', value=member.created_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name='Joined at:', value=member.joined_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name=f'Roles ({len(roles)})', value=" ".join([role.mention for role in roles]))
embed.add_field(name='Top Role:', value=member.top_role.mention)
embed.add_field(name = 'Bot:', value = member.bot)
await ctx.send(embed=embed)
ahhh never thought of that ty
👍
Hello, I had a question about the select menu, I wanted to know how to send it with Embed?
With discord.py and an interactions library?
With those, most of them just extend the send or reply methods with a components kwarg, so just use both the embed and components kwargs
yes
what would be the event for checking when someone (specifically my bot itself) stops talking/playing audio
@fast hedge , *, description
light mode, why D:
Ill change it just for you
Guys need some help
Can you elaborate
Guys I need a good host to host my dashboard and my bot together so is there one u guys know that can do this?
Yeah sorry my bad. Just do ctx, *, description in the command arguments.
Might have typo'd this
@slate swan All good man. Thank you
Yeah no worries cool
can anyone give me tips for creating discord bot
A collection of tips for discord.py to help make better, more efficient bots.
yepp
@commands.has_permissions(manage_server=True)```
thanks @wicked atlas
then you can do get role of that member and then check permissions of them
If there are already messages, how do I check that the thread has already been confirmed so it it doesn’t resend the confirmation over and over again? https://hastebin.com/zicupaxuno.properties
is it hastebin or pastebin?
Hastebin
I- idk what that has to do with my issue but ight lmao
can anyone suggest me youtube video where discord.py is explained clearly
tbvh, nowhere, you can find tutorials for specific d.py things on youtube, but there is no video where everything is explained
what can i do?
read the docs
well ok thanks
Which is better heroku or replit
for which purpose?
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Hosting bot
replit and heroku are not meant for hosting discord bots
^
Ye but one has gotta be better then one
replit is better , yet not suggested to use
doesnt matter which one is better, the point is that hosting a discord bot in either of them is not reliable
Hmm ok
yeah , both of them can lead to a ratelimit :p
how am I able to limit a command use to a certain channel
if statement
'if ctx.channel == (ID) 'work?
Working absolutely fine. Thanks !
ctx.channel.id
thank you!
np
wdym by clearly?
they should explain every important thing about it
you dont understand it?
i havent watched youtube video yet
so i came here asking suggestions
meaning
nvm
A collection of tips for discord.py to help make better, more efficient bots.
i got this
lmfao?
what dont u understand smh they all explain it clearly except those videos where they let you copy & paste lol
!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.
Make sure you have enable intents
You have import intents in your main file?
i am doing it in one file only
Go to discord developer portal
ok
And show me
which tab?
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.
ok
Restart your bot. Create new token and try again
!pastebin
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.
What happened?
Show me your code
Yes
with all features
It is a challenge to make a bot in one file
I got it
pls tell me
Fk
In get_channel
Weird, should have raised an error
Where's ctx tho....?
it didn't
You wrote it wrong
Weird. Anyways fix it now
no ctx here
Should not return error?
Ah, okay. It's fine
That's what I mean
the channel id is an int right?
what is this?
discord.Embed
discord.Embed
Capital E
Ok
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
why does it say 1 users? i used
{len(client.users)}```
bcuz your its only counting it self
cuz client.users client.user specifies only it self
so what client.users does?
do you have members intent on?
yeah
!d discord.Client.users it returns a list of all the users
property users: List[discord.user.User]```
Returns a list of all the users the bot can see.
are you using it after the bot is ready?
since users wont be cached until it is
hollon ima readd it to the server
nope does not work
prob its the version cause it worked on my other code
nope its not
Nvm i fixed it i did not added py intents = intents
¯_(ツ)_/¯
bot.remove_command("help")
👍
?
The code
Will it work?
Sure
good
guys for embedspy embed = discord.Embed() embed.setThumbnail(can i use a png directory here?)
m
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
And u need a url bro
yea, im talking about the url
in a string?
Yups
is the name.png a string?
Edited it. Fine now?
What about file=discord.file('dir') ?
okk
It needs a url kwarg bro
kk
🤔
your doing ctx.send(embed), try ctx.send(embed=embed)
u also need a discord.File object and when u send it u also need to add (..., file=file)
....?
on the set_thumbnail line?
Hi, I have dict of permission values for a member that is key perms, example: administrator etc... So how do I check if those dict of perms are there in a member?
I'm using member.guild_permissions for checking if member has that permission
Guys is there any host familiar to you that can run a quart app discord bot and one IPC together
where do i put it tho?
on the ctx.send()?
.send(embed=embed, file=file)
aight
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
i got it
Anyone?
I'm doing dict bcz I want specific perms to show up and also to remove _ even tho ik we can do it like .title() and replace
classmethod advanced()```
A factory method that creates a [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") with all “Advanced” permissions from the official Discord UI set to `True`.
New in version 1.7.
There
Anyone?
does fp stand for filepath?
Yea
Hey guys, I'm wanting to make a 6 mans bot. Where players can q up for a game and it will randomly assign them in teams etc. I was wondering how I would host the bot, and the best way to go about a database for the win/loss stats.
I've only ever created very simple bots ran off my own pc.
This returns mod perms?
are you willing to pay for vps?
if not, you are very limited
yeah, given its not to expensive
how much?
like 2-5 bucks a month
it depends on what perks you want on your vps
like memory and stuff
Does it make that much of a difference
As in is it worth it
hello can someone show me how to use the spotify class in discord.py?
@client.event
async def on_message(ctx):
guild = ctx.guild
rol1e = discord.utils.get(guild.roles, name="susmommuted")
if (ctx.author.has_role(rol1e)):
embed = discord.Embed(
title = '',
description = '',
colour = 0
)
embed.set_footer(text='By oSeatch#6969')
embed.add_field(name='Disqualified!', value=f"{ctx.author} Has Lost!", inline=False)
channel1 = client.get_channel(890476025996275732)
await channel1.send(embed=embed)
await ctx.author.remove_roles(rol1e)``` `AttributeError: 'Member' object has no attribute 'has_role'` getting this error ._.
do tht if like
if user.role in role
yeah, again depends what are going to store in it
what
i got it
ok nice
i didnt
what
what do i replace with ctx.author.has_role(rol1e)):
role = discord.utils.find( lambda r: r.name == 'Mod', ctx.message.guild.roles)
if role in ctx.author.roles:
^^^
on_message doesnt have a ctx parameter, it only has the message parameter
then he might chnge all ctx to message
not quite working
role = discord.utils.find( lambda r: r.name == 'susmommuted', ctx.message.guild.roles) AttributeError: 'Message' object has no attribute 'message' eh
client events do not have a ctx parameter
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
did you change that?
do u wanna attach the image into the embed?
yea i did, it didnt have the message parameter, it had the ctx one xd
ahhh ok
yea
i fixed it kekw (after someone gave me the code lmao)
Hello
embed.set_image(url=[imageurl])
it can be simple as await ctx.send(embed = embed, file=discord.File('idk.png'))
Try this ```py
embed.set_image(url="attachment://file.png")
idk if it works tho
that wont work its not a url
is there any way i can limit the amount of times OnCommandError can be raised untill it does nothing? kinda like putting a limit on how many times a command that is on cooldown can be called
aint url
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
Try .send(file=file, embed=embed)
yes its a url
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
works for me though
ok then
can u send the full ctx.send code of that
ill check with it
im stupid
ok
is there anything i can use to make a command that will list all members with a specific role?
!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...
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
!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")...
How to change prefix for a single cog file?
its something like
class Anything(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.prefix = "prefix"
async def cog_check(self, ctx):
return ctx.prefix == self.prefix
i know you would have to put something in your main file but i forgot and think staright cuz its like 11pm
i just found a stackover liknk that will solve your prefix problem https://stackoverflow.com/questions/63105582/different-prefix-for-each-cog
i did the first part similarly, and you can read the second part
imma go
bye bye
we use <#channelid> to tag channel right?
Hello I use repl and I want keep a few commands in a different .py file but also work in the main so it can be clean, is there anyway to do that?
cogs
how do i use them i found the page kind of confusing
cogs are used to make seperate files and then connect them to the main file
yeah
yes
wait i have a vdo for u
<# channelid> with space between # and channel id?
or without space?
without space, yes
ok
In this video, we learn about cogs and how to implement them in a discord bot.
If you have any suggestions for future videos, leave it in the comments below.
GITHUB: https://github.com/Rapptz/discord.py
DOCUMENTATION: https://discordpy.readthedocs.io/en/latest/
OFFICIAL DISCORD.PY SERVER: https://discord.gg/r3sSKJJ
JOIN MY HELP SERVER: https:...
prolly the best tutorial out there ngl
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
ok i still dont get it
heyo bot is not taking the whole question its only making the first word as the question and not the word after space in as question
@client.command()
async def test(ctx):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="susmommuted")
members = discord.utils.get(role.list.Members)``` something like this?
?
remove the , after question ._.
kk
async def _8ball(ctx, *question):
(ctx, *, question): would be needed for sentence no?
client = commands.Bot() i know enough
why do you need the underscore?
any idea what im doing wrong?
Just use 8ball i dont get why its _8ball lol
@client.command()
async def test(ctx):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="susmommuted")
members = role.list.Members
ctx.send(members)``` tried this too ._.
Because in python functions may not start with an int
oop i forgot about that
!e ```py
def 8ball(inputs):
return 'string'
8ball('something')
@cloud dawn :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | def 8ball(inputs):
003 | ^
004 | SyntaxError: invalid syntax
anyone?? .-.-.-.
got it wayyy back
What are you trying to do?
yesuu
So the command should be like
!test @winged charm
bot :
- seatch
- some random
- idk
wait i pinged someone on accident..
dont ping random people bruh
i didnt lmao
you did moving on
it auto pinged for some reason
he had it comming
i just did
then you hit tab moving on
I still dont get it you want to show a profile?
i want to list all members with a specific role
Ahhhh
see i told u kayle
any clue on how to do it?
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
i cant figure out how to use this.. that's the thing..
why not something like this? ```py
if role_id in [role.id for role in (member.roles or ctx.author.roles)]:
await ctx.send('Role found')
🧠
@client.command()
async def test(ctx):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="susmommuted")
members = role.Members
ctx.send(members)```?
i try this it hit me in the face

wha ok
Pretty big api call ngl
@lone aurora use this
okok i try
Yeah but I don't know what he really wants just came now and saw the question lol
my on_member_join command is not working properly
okay
what ok
@client.command()
async def testing(ctx):
role_id = discord.utils.get(guild.roles, name="susmommuted")
member = role_id.Members
if role_id in [role.id for role in (member.roles or ctx.author.roles)]:
await ctx.send('Role found')``` like this?
i have asked one of my friend his on_member_join command is also not workin
g
send the code
wait
didnt work daidjadja
wait i will check that after
intents enabled?
ofcourse it did not
ok wtf wait i need to see why my entire bot breaking.. no cmds working brehhh
yea
code and dev portal?
do you have on_message event?
wait
If anyone knows MongoDB please help me in discord bot ;-;
#databases
yea, the problem was there, i think removing it might fix da bot
no
instead of the @bot.event decorator, change it to @bot.listen()
ill try it but for now the command itself isn't working..
alternatively you can add
await bot.process_commands(message) to the bottom of the @bot.event
why are my curly braces not like in lukas's video?
first do what I said.
code
okok
listener()
huh
naw
If you are going to copy code then you won't understand.
@client.listen()
async def on_message(ctx):
role = discord.utils.find( lambda r: r.name == 'susmommuted', ctx.guild.roles)
if role in ctx.author.roles:
embed = discord.Embed(
title = '',
description = '',
colour = 0
)
embed.set_footer(text='By oSeatch#6969')
embed.add_field(name='Disqualified!', value=f"{ctx.author} Has Lost!", inline=False)
channel1 = client.get_channel(890476025996275732)
await channel1.send(embed=embed)
await ctx.author.remove_roles(role)``` how's this diabolical?
!d discord.ext.commands.Bot.listen
client = commands.Bot(command_prefix='c!', intents=discord.Intents.all(), case_insensitive=True)
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
He never turned on intents ;-;
sounds like something i would do
i am trying to learn and even listen to lukas, i just started yesterday and came here to learn about it only
you mean @bot.listener()?

iz dis ok
bruh
Yes.
i- i- w h a t
why would he do bot if he has client in bot defination
what no
If you make it an event you will not get it in the bot command list
on_message is an event
ain't it @bot.listen() , the decorator for the event
yes i know?
can someone help me understand this?
i need help
i dunno i just use cogs.
don't copy code- read the docs and understand
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
please help
No since this code is not even good.
oh-
with what?
@client.command()
async def testing(ctx):
role_id = discord.utils.get(guild.roles, name="susmommuted")
member = role_id.Members
if role_id in [role.id for role in (member.roles or ctx.author.roles)]:
await ctx.send('Role found')``` just please, how can i fix this to show all the members in a specific `role`
you have to specify wat help you want
im getting this error
Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.environ['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
Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.environ['TOKEN'])
File "/usr/lib/python3.8/os.py", line 675, in getitem
raise KeyError(key) from None
!d discord.ext.commands.Cog.listener meant this
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
oh yeah that's for cog
you don't have the TOKEN env var defined
first of all, it is members, not Members.
here the code https://paste.pythondiscord.com/upinavewov.go
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
@client.command()
async def testing(ctx):
role = discord.utils.get(guild.roles, name="susmommuted")
print([member.name for member in role.members])
@client.command()
@commands.is_owner()
@commands.has_permissions(manage_channels=True)
async def help(ctx):
embed=discord.Embed(title="Embed Bot", color=discord.Colour.random())
embed.add_field(name="\uD83E\uDDCA `"+prefix+"help`", value="Shows all commands' info", inline=False)
img = ctx.message.author.avatar_url
embed.set_thumbnail(url=img)
embed.add_field(name="\uD83E\uDDCA `"+prefix+"embed <message>`", value="Sends embeded message\n *(Requires 'Manage Channel' Permissions)*", inline=False)
embed.add_field(name="\uD83E\uDDCA `"+prefix+"about`", value="Shows info about the bot", inline=False)
embed.timestamp =datetime.datetime.utcnow()
embed.set_footer(text="Requested by {}".format(ctx.author))
await ctx.reply(embed=embed)```
I recommend subclassing
So should I divide the program?
yeah you can read the pinned messages
Or is there any other way to check if a user has a perm.......other than ```py
@commands.has_permissions(manage_channels=True)
nice it works now
genios
y am i get no help
@slate swan define your TOKEN
Someone knows where i can host both bot and website? (Rather if the server is dedicated)
well then, adios
not for free
but there are plenty of hosts out there
infinty free
How do i have the bot send emojis??
paste the emoji in code
Use the emoji ID
yea lmao
\:emoji:
carp i meant stickers
I don't think bots can use them, can they?
I know, money isn t the problem, but i m pretty new with hosting and i prefer to not waste money
plerase help
wups
is there any way i can change the syntax in which it sends the message?
Like rn its
['user1'],['user2']
Can anyone help me toooooooo
without sub classing
@slate swan what do u need help with?
How do you want it?
this
i cant copy the link :(
something like
[User1]
[User2]
Trust me, it is way more easier with subclassing
it looks nicer and easier to read imo
I never did subclassing
whats the worst that could happen if i were to host two different scripts using the same bot token?
Ah
HELP PLEASE
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3.10/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3.10/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3.10/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
nah any command is not working
See
one runs, one gives error
like some messages could go unlistened or not go through yea?
HELP
oh-
U should do command(name="help") and name the function something else
CHECK THIS LINK AND HELP PLEASE I WILL DIE I NEED PLEASE https://replit.com/join/vfqgofkqkh-yaboicleetus
With?
it says that bot is running so...
@slate swan calm down.
@client.command()
async def testing(ctx):
role = discord.utils.get(guild.roles, name="susmommuted")
members = "\n".join([member.name for member in role.members])
await ctx.send(members)
Please paste the code here
It is not hard, and there are a lot of tutorials, it will take you less than half an our
also what are shards
CHECK THIS LINK AND HELP PLEASE I WILL DIE I NEED PLEASE https://replit.com/join/vfqgofkqkh-yaboicleetus
No one would click that
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.
!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.
bruh
Hmm
that...
andd error Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.environ['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
Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.environ['TOKEN'])
File "/usr/lib/python3.8/os.py", line 675, in getitem
raise KeyError(key) from None
KeyError: 'TOKEN'
thats not too big XD
how to jinx yourself
Token ain't set as an environment var
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
....?
key token not defined
nicee thanks a ton man
import music
???
how can i run multiple instances on like the same bot token
🤦♂️
let me try some thing
you know there are things other than yt for music
isnt that the same thing as 'shards'
They'd still break ToS lol
@slate swan does it work BTW?
music bot isn't breaking rules right?
If you can name the site that it is legal on i'll help him rn.
They are
I remember I saw something like this somewhere in github: ```py
if ctx.author.guild_permissions.manage_channels == True
return 1```
HOW what about rhythem,groove
Eh, just use commands.has_guild_permissions()
thats why they stopped...
They don't exists anymore loool
They are down cz of the same reason
f youtube
youtube just announed an official collab with discord to implement it themselves and murdered all the bots
They do... The owners never deleted those bots bro
ikr
I need to use command.is_owner or command.has_permissions together
Let's do keep it civilized.
Mh yes it works, so?
Ah okay
so let me try
Essentially rendered useless is not existing for me imo
i forgot its name
If you use command.is_owner the only the guild owner can use that command
lmao i think umm youtube stopped making it work i think
bot owner i think
bot owner
Well, as the owners said, they are doing something else
Lel
yt sued em
You know what?
boy im delete now
C&D not sue
what are.... 'shards'
welll how else would i play music
or is that a java thing
although they let off rythm and groovy kinda easy.
in my server
host an illegal internet radio perhaps perhaps
cuz how would i rickroll my dev staff lol
?
if youre at the point of putting in the effort to make a music bot you might as well ig
shards are multiple instances of the bot to reduce stress on other instances.
The features.
Wait so rythm too is shut down?
Uhhh?
What i believe yeah
how can shards work but running two diffferent instances of a script one will break
yea
It is also down, yea
That they are working on, groov
yep
How many servers is your bot in? Also does not work like that.
on 15th or 14th september
hi, i made a snipe command, and i want the bot to check only the channel, not the entire server but now it keeps saying theres nothing to snipe
sniped_messages = {}
@client.event
async def on_message_delete(message):
sniped_messages[message.guild.id] = (message.content, message.author, message.channel.id, message.created_at)
await asyncio.sleep(3600)
@client.command(aliases=['sn'])
async def snipe(ctx):
channelid = sniped_messages[ctx.guild.id]
if channelid == ctx.channel.id:
try:
contents, author, created_at = sniped_messages[ctx.guild.id]
except:
await ctx.reply("There's nothing to snipe, bro")
embed = discord.Embed(title="Last Deleted Message", description=f"> {contents}", color=discord.Color.random())
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=f"{author.avatar_url}")
embed.set_footer(text=f"sniped by {ctx.author.name}#{ctx.author.discriminator}")
await ctx.reply(embed=embed)
else:
await ctx.reply("There's nothing to snipe, bro")
probably will be just one
U just run simply. Don't worry about the shards. The library takes care of that
i am making smthn that will be kinda user hosted
Like all things should lol
Then why use shards
like each individual user runs it
Indeed
so itll end up with multiple instances regardless
Soooo? As long as u don't give them the token, don't look into shards
DON'T give your token to anyone
They can kill your bot, nuke your serer and stuff
nah bot wont have power anyways and i trust these peeps
Bruh
its like a convinience bot we;re working on
.
python in the future ```py
from discord import Main
Main('*#U9jd3j93JD(#*u938ddk--3-3dj(#((#')
you can have diffrent bots name "Bot Name 2" or "BotName 3"
so... even if everyone has the same scripts running (same token) bot wouldnt break too much yea?
bot give error saying bot is already being ran
Why I am getting these errors from external scripts when I run a command
Why not do something like
sniped_messages: {channel_id: message_object}
As channel ID is unique. And in the event, just add an if statement to check for the channel
can i use shards to avoid that
Not enough. We need the full traceback
ok
like every instance acts like a shard
Bruh no
no
why doesnt that work?
What....? That's your code only
How many servers is you bot in?
its just one server
ohh nvm
U r getting the shard concept wrong
you are saying "can i use the same keyboard for 10 pcs?"\
Bot is now Online
F:\Python\monke bot\main.py:45: RuntimeWarning: coroutine 'Message.delete' was never awaited
msg.delete()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in command bant:
Traceback (most recent call last):
File "F:\monke bot\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "F:\Python\monke bot\main.py", line 22, in bant
await member.ban(reason=reason)
AttributeError: 'Context' object has no attribute 'ban'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "F:\monke bot\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "F:\monke bot\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "F:\monke bot\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'ban'
``` Bant and kickt are commands lol
does that check channel only?
but there will be several instances of the script
Then worry about sharding over 2499 more servers.
await message.delete()
i just want several instances to exist epacefully
it's a coroutine
ya ?
@timber crescent
Oh lord
can sharding also do that as a side effect?
it needs to be awaited
So it should delete the ,essage?
oh-
I think I ma doing that by using await
so sharding essentially breaks the bot functions into several scripts?
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.
U don't do it, the lib does
!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.
Basically
so do i still need [message.guild.id] because i have sniped_messages[message.guild.id]
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='.')
Filter = 'giant'
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle, activity=discord.Game('Hello there!!'))
print('Bot is ready')
print('Bot is now Online')
@client.command()
async def kickt(member: discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def bant(member: discord.Member, *, reason=None):
await member.ban(reason=reason)
@client.command()
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
@client.command()
async def delete(ctx, message):
await ctx.channel.delete(message)
@client.event
async def on_message(msg):
for word in Filter:
if word in msg.content:
msg.delete()
await client.process_commands(msg)
welp in that case idts the instances will function quite how i want them to
Nope... As I said, the channel IDs are unique
ctx, member
oh
so my best bet is to either have a central script that has the bot acess or several bots ye?
Yes
do await msg.delete() under the on_message
ok
yep.
thatll be quite the hassle but a managable hassle i suppose ty for the help
if word in msg.content:
await msg.delete()
you forgot await here, and
@client.command()
async def kickt(member: discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def bant(member: discord.Member, *, reason=None):
await member.ban(reason=reason)
are missing the ctx arg


