#discord-bots
1 messages ยท Page 480 of 1
from discord_slash import SlashCommand
client = commands.Bot(command_prefix='k.', intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
@slash.slash(name="ping", description="sends pong")
async def ping(ctx):
await ctx.send("**Pong!**")
It doesn't work without any error.
anyone have an autorole system I can use?

I'm confused to as why you are even telling me this and what it has to do with what I was talking about
how to get when new chanell** is created
!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/stable/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
Is there a command decorator to make commands case insensitive or would I have to manually do it?
Also came somebody explain to me the difference between has_permissions and has_guild_permissions
has_permissions is based on the channel perms and has_guild_permissions is there overall perms for there role
Would there be any downsides to using has_permissions instead of has_guild_permissions?
does anybody know what does this mean i just dont get it still its a async praw command:
if not submission.is_self
depends has_permission mean you have to manually go to everychannel and set the perms but it can be useful for VERY specific things has_guild_permissions is the easiest for things like mod commands
what are you trying to do?
im trying to get reddit submissions that are only images and text and not only text but i got this command that i know what it means the is.self but i dont understand what the whole thing means im just very confused
I'm just guessing because I don't have a lot of experience with it but I think its checking if itself made the post
No idea why you would really want to do that
Since there is not in there
@final iron You can solve this one
Its checking if it didn't make the post
wdym
it checks if the submission was not posted by the authenticated user
which is you
or whoever
thank you
Oh nice just figured out that the person who made the discord.py documentation doesn't live in the us
Thats cool ig
Like created yourself?
that's not how we help here....
Not create you commands
*event
some materials that you can use are like
!d discord.on_raw_reaction_add
huh
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Me when bot
!d discord.Reaction.emoji
The reaction emoji. May be a custom emoji, or a unicode emoji.
Oh d is for documentation
yes
Makes sense
which you can convert to str
for create_role in the documentation it says colour is Colour, int so what exactly does that mean
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").
There is an alias for this called Color.
`x == y` Checks if two colours are equal.
`x != y` Checks if two colours are not equal.
`hash(x)` Return the colourโs hash.
`str(x)` Returns the hex format for the colour.
?
lemme check
colour=
!d discord.Guild.create_role
await create_role(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
For the integer
but as I see, it could just have a value
If I used Colour.from_rgb I could have the user pass in the 3 numbers right
like 100 50, 125?
check it in the docs...
alr
Yup I see now ty
discord.Colour().from_rgb(r, g ,b)
it's a classmethod
you don't need to create it as an instance
discord.Color.from_rgb(r, g, b)
What are the options now that dpy has been archived?
dpy.
Can somebody link me to the documentation to delete a role I can't seem to find it
role.delete?
!d discord.Role.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the role.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this.
there are many good ones. I personally used disnake, combination of fork of discord.py and disnake. (not advertising)
How would I parse in the role I want to delete?
I don't see it in the parameters
you would need a discord.Role instance (construct it by yourself is impossible) use Guild.get_role() instead
so discord.utiles or whatever it is?
get_role(role_id)```
Returns a role with the given ID.
!d discord.utils.get or this yeah
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/stable/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...
Thank you
How do I have my bot press a anothers bots button
im trying to have my bot press another bots button and that bot adds a role to my bot
Bots cannot interact
@raven.command()
async def prefix(ctx, *, message):
print(f"[{Fore.MAGENTA}RAVEN{Fore.WHITE}] [{Fore.MAGENTA}{current_time}{Fore.WHITE}] โบ Command Ran {PREFIX}{Fore.MAGENTA}prefix{Fore.WHITE}")
if ravenconfig.get("Raven-COMMANDLOGGING") == "on":
with open("log/Commands.log", "w") as l:
l.write(f" Log: [{current_time}] Prefix Was Ran By User {raven.user}")
if ravenconfig.get("Raven-COMMANDLOGGING") == "off":
pass
with open("Raven.json", "w") as r:
newPrefixData = {
"Raven-TOKEN": TOKEN,
"Raven-PREFIX": message,
"Raven-DELTIMER": DELTIMER,
"Raven-COMMANDLOGGING": LOGGING
}
r.write(json.dumps(newPrefixData))
NEWPREFIX = ravenconfig.get("Raven-PREFIX")
raven.command_prefix = str(NEWPREFIX)
prefixEmbed = discord.Embed(
color=0x483248,
timestamp=ctx.message.created_at)
prefixEmbed.set_author(name="Prefix was changed :heavy_check_mark:")
await ctx.send(embed=prefixEmbed)```
why is it in my prefix command
when i run it, it changes the prefix but it doesnt allow me to use the new prefix
i realised i needed to reopen the json and define NEWPREFIX but what do i do then?
Myabe you have an actual reason for this but it sounds kinda sus
You never reload the json, it's not aware of the new values.
How would I store permission attributes like administrator=Trueall together?
yes i did lol
You don't
Im creating a command that makes a role with certain permissions
learn python or re-read it
do it again or ill point it out again
Nope
from the already established
Still the old json
oh
From before the new values were dumped
ok
Which if you listened, I pointed out, but it seems you were too busy being a dick.
not to you
And?
Hoi
so reopen
yes.
yes there is stuff in the json file
yea that still doesnt work lol
it should go like
Your json became invalid
never heard of that before
There should be L:C of where the json is invalid
line 1 column 1
What is the json
How would I store permission attributes like administrator=True?
Would I use a tuple?
What are you trying to do
Wdym
Ik but how would I store it
In a tuple?
I need to store it in a variable
Because I need to define a lot of permissions
like in a database or as a parameter?
dw abt it
Just a variable
like permissions =
You can create a discord.Permissions object
And call .update
And that takes a k: v pair of permission: bool
I don't think im really explaining what I need help with well
An example of what im trying to do is
permissions = [
administrator=True
manage_messages=True
]
Something like that except working
Sorry its a bit late so im kinda so rn
Oh alr
So would it be administrator: True?
If its not can I just get an example please?
Oh alr ty
Ill try it out
Btw if I don't define the permission will it default to False?
For?
In the dictionary
how do i make my bot say Command Not Found when someone try saying a command thats not there
If I parse the dictionary for a roles permissions and certain permissions aren't defined will they default to False
If a key doesn't appear in a dictionary and you try to index it, it'll throw a key error
!d discord.on_command_error
Oh okay so ill have to define everything then
discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
And use commands.CommandNotFound to compare isinstance
Well what are you doing with it
Im creating a command that will create a role with certain permissions
update(**kwargs)```
Bulk updates this permission object.
Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.
make a permissions object then update it with your dict
You know what imma just finish this tmr
Could This Work?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(':heartbroke_no: **Command Not Available**')```
This is for a Missing Required argument as the name suggests
Replace commands.MissingRequired.....
!d discord.ext.commands.CommandNotFound with this
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
replace it with
commands.CommandNotFound(message=None, *args)
No , the () is not required
just commands.CommandNotFound
in case you want to get the name of command user used , you can use ctx.invoked_with
Thanks It worked
glad to help :3
You know what lemem try again to explain
How can i make the bot sends a message in there server as they added it?
Im using this await guild.create_role(name="Moderator", permissions=, colour=rgb_color) to create a role. I want permissions= to equal a list/tuple/whatever that holds the roles permissions like this
administrator=False,
manage_messages=True,
manage_channels=True
My issue is I don't know what to store those permissions in
๐ค anybody have any ideas on how one would allow a discord bot to do a thing when it receives a private message?
Hi, I am trying to make a bot that plays music, however, when I run this command (below)
@bot.command()
async def stop(ctx):
if ctx.voice_client is not None:
await ctx.voice_client.stop()
await os.remove('temp\song.mp3')
else:
await ctx.send("Bot is not connected to a voice channel")
it raises the error "Object NoneType cannot be used in await expression"
Do you know what line is erroring?
there's 3 awaits there.
oh my bad
the one that errors is the stop
but if I take it out of the await it says it needs to be in an await expression
So?
Looking into it. I havent done much with voice.
gimme a moment. I think that command is wrong.
Usually it's the opposite of whatever you did to start it.
Oh ctx is set to the user of the person who called the command btw. you need to set it to the bot
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild) #gets the bots voice clients by guild.
await voice.stop() #try this
@opaque trellis
Alternatively, you could just do a force disconnect and reconnect ๐
that's true, but I need it to be able to delete the mp3 file as well
No. Just disconnect the bot from voice. do the thing to the MP3 file. then reconnect. not as efficient or good, but it's AN solution
hi guys, someone can made a bot of games?
๐ฆ
@bot.command(name='summarize')
async def summarizer(ctx,*,args):
text = int(args)
tokenizer = PegasusTokenizer.from_pretrained("google/pegasus-xsum")
model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")
tokens = tokenizer(text, truncation=True, padding="longest", return_tensors="pt")
summary = model.generate(**tokens)
x = tokenizer.decode(summary[0])
await ctx.channel.send(x)
nothing is happening here
what is a pegasus tokenizer?
Pegasus is an AI model used for text summarization
neat
and the toxinizer is needed to toxinize the first input of information so that it could change into the summary
Well if nothing is sending, perhaps try printing out each variable to make sure they're working
Code: #Pfp command to view somones pfp! @bot.command() async def avatar(ctx, *, avamember : discord.Member): userAvatarUrl = avamember.avatar_url await ctx.send(userAvatarUrl) Error: Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke await ctx.command.invoke(ctx) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke await injected(*ctx.args, **ctx.kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped raise CommandInvokeError(exc) from exc nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
i think nextcord does member.avatar.url or is that pycord?
idk
try avamember.avatar.url maybe
may or may not work
odd why doesnt this work
It should the same thing because discord.py stopped in development
isn't nextcord based on the latest master release
then it should be avatar.url
avatar_url*
Mine works as avatar_url
because your discord.py version is outdated
;-;
ahhhh
let me see
so like this? @bot.command() async def avatar(ctx, *, avamember : discord.Member): userAvatarUrl = member.avatar.url await ctx.send(userAvatarUrl)
yup
Wait nevermind @slate swan is right. I was using the wrong command LOL
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'member' is not defined```
@slate swan
why make a variable just send it lmfao

You need to tag someone.
@commands.command(help='[Sends the avatar of the mentioned user.]')
@commands.is_owner()
async def avatar(self, ctx, *, member: discord.Member):
userAvatar = member.avatar.url
embed = discord.Embed(color = member.color, timestamp = ctx.message.created_at)
embed.set_author(name = f'Avatar of {member}')
embed.set_image(url = userAvatar)
embed.set_footer(text = f'REquested by {ctx.author}', icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)
not only that,
he made his variable name avamember
so it's avamember.avatar.url
not member.avatar.url
Will member.avatar.read() work for default profiles?
Mhm
wait
Waiting
nextcord is 2.0
So that avatar command is from discord.py
Hi ya there I need some help. I made some kick and ban commands but turns out anyone can use them, anyone know how to make it role specific?
Built-in Checks for the commands extension of discord py - Checks.py
under client.commands()
put
i wanted to know how to find if a message contained some keywords which i cant find with message.content
lucas ban is bad
@commands.has_guild_permissions(perm here=True)
@commands.has_permissions(ban_members=True, kick_members=True)
# e.g. this command will require both kick and ban permissions
# Check if user has all of the passed permissions
@commands.has_any_role("role1","foo",11132312313213)
# Check if user has any of the roles with the names "role1", "foo", or the role with id 11132312313213
guild
anyhelp ?
is the overall perms of the role
ok
cuz there was a way in java but idk how to do that in python
so if I have manage messages for a role it will be possible for every channel
and this is in the client.command(here) right?
works both
bruh
so this works as well: #Bans a User @bot.command(description="Bans a member") @commands.has_guild_permissions(ban_members=True) async def ban(ctx, member: discord.Member, *, reason=None): await member.ban(reason=reason) await ctx.send(f"{member} was banned!")
so do i replace client.command?
stop spoonfeeding code
??
im really sorry
no its a command decorator add it to the command
you cannot do it without using message.content ,(in any language)
the func/attribute would be using message.content inside its structure for sure
You can use the has-roles decorator.
@commands.has_any_role('bot','Bot','Owner')
How can I target messages sent by a specific user so I can remove them?
you could literally do py if "the text you want" in message.content:
bro
if the role updates its name you have to go back and update it
in something like a purge command?
Then dont update its name?
so like this right?
use role ids
oh
No
thx
no
I think you mean includes();.
It's a command decorator like @client.command()
where is your client.command() ??
ill try both
includes() is in Java and JavaScript and not Python.
it was for java , wont work in py
oof
The check should be below the decorator.
Add the @commands.has decorator below @client.command
Below, so the command would be registered with the checks.
@commands.has_guild_permissions(kick_members=True)
async def boot(ctx......)```
!code and yes, correct.
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.
something like that
this right, just confirming sorry for being annoying
kick_members.
yup
thats it right?
And this is a Python help server, I don't think it's annoying to ask?
nothing else required
should be
Thanks for you time!
Change Kick Members to kick_members and you should be good to go.
No problem.
Also I suggest adding if statements to check whether the bot would be able to kick that member or not. For example, check if the member's top role is above or equal to the bot's top role.
!d discord.Member.top_role
top_role```
Returns the memberโs highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
How do I view my avatar if I have a default pfp in 2.0? The error I get: ```py
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'
if member.top_role >= ctx.guild.me.top_role:
How would I purge the messages from a specific person?
This is way more effective than what I wrote lol
Check if the message.author is the user you want.
Not the author. Like, say I wanna do $clear_messages @<user>, i want it to find all the messages in the channel from that user and delete them.
You would pass a function to the check kwarg of purge
There you return if the message author is the same as the user you specified
!d discord.TextChannel.purge
await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting botโs messages
@bot.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, id="888819465020649533")
await member.add_roles(role)```
so this is my autorole code
Id's aren't strings
but it doesnt work
purge has a check kwarg. You could do
check=lambda m: m.author == user
and doesnt give me errors


ohhh
You don't need discord.utils.get
You can just do guild.get_role(id)
Since you have access to guild ofc, from member.guild
@commands.command()
async def clear_messages(self, ctx, member: discord.Member):
check = lambda m: m.author == member
await ctx.channel.purge(limit=amount, check=check)
``` would work?
when you do !help how do I get the descriptions to display there instead of when you do !help command
Oh I forgot to specify limit. but I can do that in a moment
Whats the point of assigning a variable as a lambda instead of passing the lambda directly
Kinda defeats the purpose of a lambda here
I think so. I expected you to put the check= in the parameters.
As andy said.
just put a description kwarg in the command for it to display there
@commands.command()
async def clear_messages(self, ctx, member: discord.Member, amount=10):
await ctx.channel.purge(limit=amount, check=lambda m: m.author == member)
```?
imma run it and see I guess
@client.command(description = f"purges x amount of messages. Needs manage messages perm. Example: {client.command_prefix}purge 3")
@commands.has_permissions(manage_messages=True)
async def purge(ctx, amount:int=1):``` where
you already did it?
let me show you
ok ig
๐ฎ It works!
I think he wants a more fancier version
you mean the help command and not the sub command
yes
no
hmmm
I mean it should be there if you didn't do anything to the help command lel
good
What's some good commands I could build? ๐ค
Hello,
Has discord.py been taken over by someone else?
hiya there im back, if the person does not have the right perms how do i send them a message saying you dont have the authority to do that
Code: ```#Unbans a User
@bot.command(description="Unbans a member")
@commands.has_guild_permissions(ban_members=True)
async def unban(ctx, *, member):
bannedUsers = await ctx.guild.bans()
name, discriminator = member.split("#")
for ban in bannedUsers:
user = ban.user
if(user.name, user.discriminator) == (name, discriminator):
await ctx.guild.unban(user)
await ctx.send(f"{user.mention} was unbanned.")
return```**Error:** ```Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: not enough values to unpack (expected 2, got 1)```
it says name, discriminator = member.split("#") is the main problem
Didnt know description worked. I've been using 'help='whatever it does'
No
i dont comprehend
Lucas
lol
Bad code
... ๐ข
how
Well I use disnake
await member.guild.unban(discord.Object(id))
why??
I said lucas ban is bad code
??
why are people using lucas ban
can i write an if statement checking if the have perms and if they dont it sends a message saying that?
and it always worked
Make an error handler or a try except
Cz people get already-written code with it and don't need to code anything themselves haha
That sticker has a gay flag
so blurry though
i still dont comprehend
like i k what youre talking about
but i dont know how to do it
!d discord.on_command_error
discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
so on the bottom
of the thing
@client.command()
@commands.has_guild_permissions(kick_members=True)
async def boot(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
discord.on_command_error(ctx, error)
Simple Error Handling for ext.commands - discord.py - error_handler.py
???
!d discord.Member.edit
await edit(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the memberโs data.
Depending on the parameter passed, this requires different permissions listed below...
Here you go
@bot.command(aliases=["checkcogs"])
async def checkcog(ctx):
if ctx.author.id == 815555652780294175 or ctx.author.id == 723032217504186389:
if ctx.author.id == 815555652780294175:
author = "Mr One"
elif ctx.author.id == 723032217504186389:
author = "Mr Zero"
for filename in os.listdir('./cogs'):
all_cogs=[]
loaded_cogs=[]
if filename.endswith('.py'):
print(filename[:-3])
all_cogs.append(filename[:-3])
print(all_cogs)
await ctx.send(f"Hey {author} All cogs are [{''.join(all_cogs)}]")
for i in all_cogs:
try:
bot.load_extension(f"cogs.{i}")
await ctx.send(f"{i} wasn't loaded")
await asyncio.sleep(1)
bot.unload_extension(f"cogs.{i}")
except commands.ExtensionAlreadyLoaded:
loaded_cogs.append(i)
await ctx.send(f"Hey {author} All loaded cogs are [{''.join(loaded_cogs)}]")
else:
await ctx.send(embed=discord.Embed(title="Nope you imposter", description="I dont take orders from peasants like you :ZOWumpusTongue:", color=discord.Color.random()))
this returns
What's wrong with that
It should be an instance of discord.Member
which points to the member you want to change nickname
Not the class itself
Here, member is your instance of discord.Member
But I think if you can't understand the difference between a class and it's instance then you should learn some python OOP first ๐
Heyy
heyg uys
do you know why my json file sometimes get overwritten with nothing?
but when i rewrite it the function works fine
Do you know how to code for the BOT to pin messages? Like i do !pin {ID}
its just really annoying
This one
Don't open it in w... Open it in r then
but eh it worked in other commands and when i rewrite the command
and r is for reading
which i already have
import discord, datetime, time
from discord.ext import commands
start_time = time.time()
class Uptime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="onlinetime")
async def uptime(self, ctx):
current_time = time.time()
difference = int(round(current_time - start_time))
text = str(datetime.timedelta(seconds=difference))
embed = discord.Embed(colour=discord.Color.random())
embed.add_field(name="Uptime", value=text)
embed.set_footer(text="Chad")
try:
await bot.send(embed=embed)
await ctx.send(embed=discord.Embed(title=f"Chad has been online for:",description=f"{text}:zo_tick_anim:",color=discord.Color.random()))
except discord.HTTPException:
await bot.send("Current uptime: " + text)
def setup(bot):
bot.add_cog(Uptime(bot))```
This shows
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'startTime' is not defined
there are way more cogs other than events
if i have a string, is it possible to send it as a file with ```py
await send(file=discord.File("string here"))
..
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
async def id(ctx,*args):
x = str("hello")
if args == "Hello":
await ctx.send(x)```
whats wrong with this
hey i am making a verify command ,how do i set different role permissions for different channels ?
@commands.has_any_role
error ?
Use args instead of *args
okay
*args is an array
args is a str with space
ahh okay thanks
np
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
@bot.command()
async def setverifychannel(message,channpel : discord.TextChannel, member =discord.Member):
if channpel == channpel:
await channpel.send("TYPE !verify to VERIFY")
unverifiedrole = discord.utils.get(message.guild.roles,name= "unverified")
if not unverifiedrole:
unverifiedrole = await message.guild.create_role(name="unverified")
for channel in message.guild.channels:
await message.guild.channels.set_permissions(unverifiedrole, view_channel=False )
await channpel.set_permissions(unverifiedrole, view_channel=True )```tried it this way ,its not working
You spelt Channel wrong
i want the channel set by the user to have send message perms but the rest to have no send message perms
thats a variable ,so doesn't matter right?
but idk want it to be id based
anyone else?
Hello, In my code i have this within my prefix command:
And this
throws an error, after the message is deleted
sorry for small/brad cropping
any reason to why this may be happening?
I have the embed deleted after 3 seconds, BTW. To cmd spam
Any help is appreciated
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.
@raven.command(aliases=["av"])
async def avatar(ctx, member:discord.Member = None):
if member == None:
selfAvatarEmbed = discord.Embed(
color=0x483248,
timestamp=ctx.message.created_at
)
selfAvatarEmbed.set_image(url=ctx.author.avatar_url)
selfAvatarEmbed.set_footer(text="Raven")
avEmbed = await ctx.send(embed=selfAvatarEmbed)
await asyncio.sleep(DELTIMER)
await avEmbed.delete()
avatarEmbed = discord.Embed(
color=0x483248,
timestamp=ctx.message.created_at
)
avatarEmbed.set_image(url=member.avatar_url)
avatarEmbed.set_footer(text="Raven")
avatarEmbed = await ctx.send(embed=avatarEmbed)
await asyncio.sleep(DELTIMER)
await avatarEmbed.delete()```
I know, thanks..
!d discord.Member.avatar_url
oh I got the error
the second part of function is executing even if the member is None
cause u didn't indent it with second condition
avatarEmbed.set_image(url=member.avatar_url```
This happens regardless of member being None or not
help
still happening
help
can anyone help me?
I indented but its still not working
i indented the avatarEmbed part
not the
How can i make the bot sends a message in there server as they added it?
Did you indent this entire section?
avatarEmbed = discord.Embed(
color=0x483248,
timestamp=ctx.message.created_at
)
avatarEmbed.set_image(url=member.avatar_url)
avatarEmbed.set_footer(text="Raven")```?
Like this like this
when they added it it sends a message in any channel it sees first
emoji = Guild.fetch_emoji("some id")
text = "Hello (emoji fetched from pervious var)"
await Channel.send(text)
How do i combine plain text with emoji?
but is that correct
should it look like that?
f-strings
ah i see, thanks!
Yw
Also, does guild have a get_emoji method?
yes it dows
yw
!fstrings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
how i make my bot sends the prefix if someone mentioned it
i tried this and i would not work
@client.event
async def on_message(message):
if not message.author.bot:
if bot.user.mentioned_in(message):
# run code here```
how can i control my bot commands from the discord itself and not from vscode?
like a command for bot owner only
you can use wait_for
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
oh
Use checks
but is it possible for an event to be in a cmd?
!d discord.ext.commands.is_owner
discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Bot.wait_for() waits for an event
When you call it
So if it is in a command, yes you can use it
suppose i have to store a string in my bot how do i do it from discord itself?
like bots like dank memer store your balance
Real quick. Whats the command to only listern to one person using id? @commands.has_something()
How to make discord bot use python in visual studio code?
Lol
That requires a database
how do i get one
How i make when you mention the bot it shows the prefix
Sorry i'm newbie
read docs
Someone?
or go to yt search discord bots using python
Where the docs?
!d discord.ext.commands.Bot.when_mentioned
No documentation found for the requested symbol.
Okay
Bruh
Wow
use an on_message event , and use py if bot.user in message.mentions..
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
I tried this
@client.event
async def on_message(message):
if not message.author.bot:
if bot.user.mentioned_in(message):```
When you mention the bot, it will consider as the prefix of bot
(if relevant, its discord.py rewrite) trying to play audio through my discord bot in voice
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn'
}
voice.play(FFmpegPCMAudio('https://www.youtube.com/watch?v=dQw4w9WgXcQ', **FFMPEG_OPTIONS, executable='C:\\FFMPEG'))
im running it through pycharm in a venv and getting Permission Error: [WinError 5] Access is denied
the error is pretty nondescript so i dont know why im being blocked from doing this, all i know is that it is coming from the above line.. does anyone know a possible fix for this? i have tried running the script as an administrator, it still doesnt work. (also, i know pretty much nothing about ffmpeg, i got the options and what not from a stack overflow thread, so if the error is related to those please direct me to the correct values)
this will be a bit bugged
you don't want you bot to send messages when it mentioned in sentences
Like
This is our @bot
.mentioned_in returns true even if someone mentions @everyone ;
Use this
you can use when_mentioned_or("prefix") , as ! a told
and then you may have a command named prefix or something
when a user uses @yourbotmention prefix , it sends the prefix
Hmm
use this , https://vcokltfre.dev/
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.
its detailed , and better than yt vids
Guys, where can I find all the types of restrictions for commands??
whats the difference between args and *args?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; (b) with YouTubeโs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
arg is for an argument , *args represents a list of arguments
@slate swan
args is an argument right?
Thank you
yes
*args is actually a tuple of arguments that are passed in
so like i wanted to make a command named "store" which will store users data or args as a variable variable will be named by the user itself
and that variable can further be used by the developer
Can I use the role one for a certain person? Cause i want it to only read by a certain user. Can I use the role and add their ID?
yeah i wanted to keep it simple so i used the word list or arguments instead of tuple
you can use roles , with ids
Perfect
for a user , if its not the bot owner , use a customcheck
int
cooldown error
@help.error
async def help_error(self, ctx: commands.Context, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"This command is on cooldown, try again after {round(error.retry_after)} seconds.", delete_after=5)
print(error)```
It's not inside a cog right?
hi, what kinds of message.content.something can i use?
well message.content is a str so all string methods, if that's what you mean
hmmmm so its a python thing not a discord exclusive thing
yep
Heyy
@bot.event
@commands.has_role('Giveaway Boat')
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('Congratulations to'):
await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`')
It listens to everyone
Like if anyone says 'Congratulations to' it replies
Yes
But it listens to everyone
I want it only to read from a certain user/bot
Can't we?
sup, can somebody help me creating a file py with a print encrypted to people get the ASCII when turns bot on but like a dependecy, so they cannot delete that file
Ok, how do I channel restrict it?
yes
where do i add this
Swap for message.author == bot.user
Oh
then how
@bot.event
@commands.has_role('Giveaway Boat')
async def on_message(message):
if message.author == bot.user:
return
if message.channel == 123
if message.content.startswith('Congratulations to'):
await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`')
Like that, obv change 123
I will
@commands.command(help='[sends the list of reminders from author.]')
async def reminderlist(self, ctx):
authorid = ctx.author.id
await ctx.send(f'Author id is: {authorid}')
await ctx.send(f'that has a type of: {type(authorid)}')
for row in self.cur.execute("SELECT * FROM reminder WHERE memberid='?'", authorid):
print(row)
what am I doing wrong? error: parameters are of unsupported type D:
sup, can somebody help me creating a file py with a print encrypted to people get the ASCII when turns bot on but like a dependecy, so they cannot delete that file
why if.?
why isnt lower() defined when scripting a bot?
it is
no
@tawdry perch
I think I messed up
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.channel == 885810026613186590(message.content.startswith('Congratulations to'):
await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`')):
whats this?
like
what are u trying to do
if u are trying to pass two values as true, u need to put and between them too
it is , you just need to use it with string
ahh
still getting error
if message.channel == (12345676543) and message.content.startswith (blah blaj):
do this
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.channel == 885810026613186590 and message.content.startswith('Congratulations to'):
await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`'):
yeah
no , you cannot compare discord.TextChannel with an int
Whaat
also why cant i use 2 variables inside a function
you can
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.channel.id == 885810026613186590 and message.content.startswith('Congratulations to'):
await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`'):
``` Check now Sarthak and Black Goku
idk, i used.... if message.channel == "roles" and message.content.lower().startswith("!add role)
do blah blah blah
your indents are still wrong
Hm
unindent the second if
tbh, why dont u use @bot.command() for this, it would be easier to mention the names etc.
i'm using bot everywhere else
bot.command
Indented
wdym u cant
Now I have a swiggle after the : last line
bro, dont use the name id, its a keyword
nah
we can
it just changes the value of x
Hello! I want my bot to block all links without allowed. I was writted code but it doesn't work. The bot receive only allowed links without sub links by same website. How ca I fix this ?
if message.content not in allowed_links:
await message.delete()```
i cant assign more than 1 one variable inside def
sends error
use message.channel.purge(limit=1) instead of message.delete()
thats what i said
yep
id is a keyword for discord.utils
!e py def id(): print(1) id()
@slate swan & @upbeat otter
Colon where
remove the : at last
new if statement should be outside first if statement
i ll just remove id from commands
indents?
Error gone. We shall see
you can name the function something else
new if statement indent is wrong
Logged in
It doesn't work. Delete the allowed links again
wait
Doesn't work
do you know what return does?
thats right something was wrong with my function
try using try and except and tell me the error
told ya id is a keyword
post code again
Me? Not really
thanks mate!
woh, very cool
anything after return doesn't get triggered
yes
What do i do?
!e
def func():
return "hello"
print("nice")
func()
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.channel.id == 885810026613186590 and message.content.startswith('Congratulations to'):
await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`')
send a screenshot
of your code
indented
ye ye
whats the error now?
indents
which one
the if statement
this was right tho
you should know lol
can someone help me with a SQL Database?
Does this look good?
unindent the await by a half
Ahh, works...
Oh
this is wrong
good
it does
Its a test BOT
replace
@bot.event
with
@bot.listen()
ok
or put bot.process_commands(message)
at the end where it still gets triggered
How to host bot 24/7 free? Use repl.it
Thank You! Works
Use repl.it
BTW, What should I use to code/host? Like when I make it public
nothing like that
How to use uptime robot? I dont know why to use
Imma search the pinned message for this
Pretty simple
I'll DM the code
hOLY
like why doesn't it come in blue like #internals-and-peps
use channel.mention()
!d discord.TextChannel.mention
mention```
The string that allows you to mention the channel.
so like channel.mention('#mailer-logs')?
no, the channel is your channel...
and don't put brackets
my bad
ok thanks
@slate swan @heavy radish
yES
why is lower() not defined in vscode?
Where do I do the coding?
don't matter
Wdym?
the code stays the same
oh k thanks
IDE?
these are IDEs
where you edit the code
it's not for running
@slate swan does not work
how come
embed = discord.Embed(title="Setup",description=f"Created a private channel called {channel.mention'mailer-logs'} in Mailer category, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
await ctx.send(embed=embed)```
Now where do I run it? Those websites?
uh
probably
but i want to mention mailer-logs
your channel should be saved in the channel variable
how do i do this
um
but what if i don't know the id before hand
..
sex in [1, 3, 5, 7, 9]
now its saying the invalid syntax is the last bracket
Show the new code
ummmm
get_commands()```
genius
sorry for that
Don't apologize
Just do your own self a favor and learn Python first
indeed
I'm not sure if me dumb saw my response
do I ping him?
ping on reply is in his name
@slate swan
sup
...
yeah it was my librarys fault i just found it out
oh
nice
maybe theyd have to update their func to get slash commands also lol
what a serverinfo code for Bot i mean i want the number of bots in that server 
idk can u help me
with this
Does anyone have a form for a good explanation of using and working with JSON?
Mostly about read json
wrong channel
well, technically...
meh
he asked about what's good for a discord bot
Read channel information ^^
still
hosting a discord bot is kinda connected to developing a discord bot
There is a text for vps in the channel history.
Check it
a helper here has once announced that he made a discord bot host
I think it's free
tho I don't remember what it was
how do i make a bot tell me who is online on a minecrft server
for free? nah
They talking about the free ones
So Pebble is bad?
github edu and free azure 
You gotta code the Minecraft part yourself
Yups
free heroku is actually good but only if your bot is a private bot only for your server
idk how to code
How free azure?
that was incomprehensible for me
How to make simple commands?
What should I host on? Like I don't want to keep code on my PC. Everyone on the web. Tell me a recommendation
somebody link the dpy guide
make rock paper scissors @slate swan
for alexzy
github education pack provides free azure and digital ocean with limitations, you cant host commercial apps iirc

