#discord-bots
1 messages · Page 760 of 1
i coded them in blocks and the command doesnt work
why the heck do people ask for pay jobs for just an easy issue when theres many people who can solve the issue for** FREE**
save your money kids
Anyone?
gn yall. Tmr I think ill make a info command with ping, uptime, cpu usage, ram usage the system specs and how many commands have been run
yo thats lit gn
That's what I don't want to!
then whats the problem?
Just make button roles IG
just comment out the error handlers, as mentioned earlier
yeah but you want to update the buttons so you know how ?
but your asking on how to?
Update the buttonS?
Why?
I don't wanna update buttons
^
I don't want the old buttons to go useless!
if your bot restarts it will not listen to those buttons which you will need to update the view with those same buttons
There must be a solution?
and i gaved it
That it will listen even after restart?
nope
Oh well imma try editing the message then with new buttons
It's gonna lag a lot.......
not really
Like I restart my bot many times
¯_(ツ)_/¯
.topic
Suggest more topics here!
I feel like a lot of people would have some opinions on this
Imo, either not force slash commands or add a higher/no cap to the amount of commands you can have
what does await member.warn(embed=em) do?
where did you get it from?
Can someone explain this error
disnake.errors.ClientException: Callback for prepare command is missing "ctx" parameter.
.warn() is not a thing
^
Im out on a limb but did you add ctx?
!d discord.Member.warn doesnt exist
Give you an error
No documentation found for the requested symbol.
Oh sir I forgot to add self
Me dumb forgot it is in a cog
how can i make a code for warning a member?
Since discord has no warning system you would have to do it yourself
You would log the warn and DM the user
Also check if they have reached the amount of warns you want to punish then at
save the warns in a db
That's what I mean log
how can i log a warn? is there any examples
Poor choice of words
You would log it in to a database
Audit log too
The reason they have a cap, is so that people don't make useless commands and finish their system's data storage or smth haha... But yea, they should increase it at least for verified bots
UPDATE my_table SET col2 = col2 + 1 WHERE col1 = "whatever"

that easy
Never learnt update
Why use it instead of replace?
would this one work?
def save_warn(ctx, member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] += 1
with open('warns.json', 'w') as f:
json.dump(warns, f)
def remove_warn(ctx, member: discord.Member, amount: int):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] -= amount
with open('warns.json', 'w') as f:
json.dump(warns, f)
def warns_check(member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
return warns[str(member.id)]```
You tell me
Run it and see
Trend
Wtf you mean you never learned UPDATE? How tf you been updating values? Deleting and re-inserting?
fr
prob
Honestly I forgor
😭
are you counting the warnings?
bad implementation, you should get a history of all his warnings, not the latest one
(by replacing)
=> rapidly changing dimensions
Should I actually learn how to use update?
i just set the amount but you can add more it was just a simple example
yes
not unless you use it
Why tf would anyone not use it?

if you don't update values ig
only using CR(U)D is not uncommon
I don't have a use case for update yet
So it's not going to be high on my priority list
so what if you do need to update a value? when is not updating something ever a thing in software that’s actually good.
not every command is edit or whatever, I don't use moderation in my private bot
how did y'all become DB Experts all of a sudden
if you wanted to update a value ofc I'd use update lmao, I won't delete and create
Okay so tmr I need to learn how to use run_in_executor, make an info command and then I'll learn update
run_in_exec is ONLY if you can't find an async wrapper ig
Yup
there are certainly alternative I think
Couldn't find anything for cross platform
hello
why do you need an async wrapper for psutil. All it does is collect data about the system 
help
I need it to work for windows, Linux and raspbien (raspberry pi)
System resources
psutil isn't that much blocking
yeah, it's speedy AF
yeah, I know what you think, even if I won't notice, I'd like it async too
Well, it's as much blocking as print is
hellp
I don't use repl, sorry
I guess google will help you on that error the for sure some other users have on that platform
theres no file called "main.py" you need one called that if you want to host your bot or so that your repl doesnt die.
I'd still prefer to have everything 100% async
I mean, psutil is hardly blocking bruv
there is
:\
It doesn't do any heavy processing
well is ur code in the main.py file?
That's not the point. I just want everything to be actually async
I understand it's not going to affect anything
Just some primal urge in me to make everything async
async def print(*args, **kwargs):
print(*args, **kwargs)
async print :DDD
but why tho. doesn’t run_in_executor spin a new thread up just to run that sync function separately.
Yea
do you even know how much processing power that takes
Can someone point out on what's wrong
import disnake
from disnake.ext import commands
import aiohttp
from disnake.ext.commands.params import Param
class PersistentView(disnake.ui.View):
def __init__(self):
super().__init__(timeout=None)
@disnake.ui.button(
label="Green", style=disnake.ButtonStyle.green, custom_id="persistent_view:green"
)
async def green(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
await interaction.response.send_message("This is green.", ephemeral=True)
@disnake.ui.button(label="Red", style=disnake.ButtonStyle.red, custom_id="persistent_view:red")
async def red(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
await interaction.response.send_message("This is red.", ephemeral=True)
@disnake.ui.button(
label="Grey", style=disnake.ButtonStyle.grey, custom_id="persistent_view:grey"
)
async def grey(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
await interaction.response.send_message("This is grey.", ephemeral=True)
class button_roles(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(PersistentView())
self.persistent_views_added = True
@commands.command()
@commands.is_owner()
async def prepare(self, ctx: commands.Context):
await ctx.send("What's your favourite colour?", view=PersistentView())
def setup(bot):
bot.add_cog(button_roles(bot))```
Too much lol
Too much processing power for a thing which is hardly blocking
U tell us
Okay fine
when u created the repl, did u tap "python" and not any other language?
I won't add the executor
yes
File "c:\Users\phoen\OneDrive\Desktop\nox-bot\cogs\button_roles.py", line 36, in on_ready
self.add_view(PersistentView())
AttributeError: 'button_roles' object has no attribute 'add_view'```
is ur main code for ur bot in the main.py file
yes
@final iron we ain't discouraging u to not use executor, we are just telling u it's useless since the lib isn't that blocking and u r just gonna waste your processing power
can i see ur code
Yeah I understand
self.bot.add_view()
why are you guys talking about repl problems in this channel :/
dms
ok
?
no
Ah tysm
get help at that time i aint doing anything
sent request
ok but youre not gonna tell me at another time
how do i make a afk cmd?
by coding
Just a tip. If it’s saying file not found and it’s obviously there. Your working directory probably isn’t right
bruh
what do u expect it to be then?
Scan for messages using on_message() if the message has any mentions(Message.mentions) process them and fetch the mentioned person's afk message from your data storage device and send it.
at least that’s what you’d do if you're looking for an afk system like dynos or something.
!d discord.Interaction.user
The user or member that sent the interaction.
Soo... author = Interaction.user?
sure
Hmm tysm
Interaction being the discord.Interaction object u get
Interaction.user
What and what is discord.Interaction
And how to get it
discord.Interaction is a class , the button click response you get is an instance of it
Yup
!d disnake.on_button_click
disnake.on_button_click(interaction)```
Called when a button is clicked.
Warning
Consider using the callbacks associated with the [`View`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.View "disnake.ui.View") instead.
New in version 2.0.
notice the interaction arg , its a discord.Interaction object
Heed the warning. Views were made for for a reason. 👌
you either would use that event , or use the view's callback
how else are you supposed to get the response?
its like saying i want to get who joined a server , but i wont use on_member_join
view's callback 👀
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overriden by subclasses.
this , its a function you will make
not much difference than using on_button_click event but will save u from checking that the button was clicked on what message
thanks!
Idk why some people hate ui.View implementation, it's just soooo clean
Ok on a welcome message do you know how to exclude a server or create a list?
You need to check the member.guild.id
Would you like some code to help?
!d discord.CategoryChannel.channels
property channels: List[GuildChannelType]```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
@disnake.ui.button(
label="Male", style=disnake.ButtonStyle.blurple, custom_id="persistent_view:male"
)
async def male(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
guild = interaction.guild
male = guild.get_role(810264985258164255)
user = interaction.author
await user.add_roles(male)
await interaction.response.send_message("Male role was successfully added!", ephemeral=True)```
What's the issue with this??
!d discord.abc.GuildChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
hey when one of your get a chance can you go down to #help-rice ?
can someone tell what's wrong here??
error pls
Ignoring exception in view <PersistentView timeout=None children=4> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Male' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\view.py", line 368, in _scheduled_task
await item.callback(interaction)
File "c:\Users\phoen\OneDrive\Desktop\nox-bot\cogs\button_roles.py", line 20, in male
await user.add_roles(male)
File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\member.py", line 944, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'```
the role variable is None , which means the id you provided in get_role is invalid
It ain't 😕
welll thats what the error says
duh-
why not ? channel.permissions_for(role/member) i dont see anything not making sense here
whats the difference between Member.premium_since and Profile.premium_since
Profile.premium_since is not a thing , Member.premium_since is
oh damn i forgor
time to study ig
ig?
I guess
!d discord.Member.permissions_in
Wait what
Ah, it's a typo
permissions_for
Not permission_for
hey can someone check this to make sure it looks right the guy that was helping went to study https://paste.pythondiscord.com/afakuhuhef.py
Why is the id in <>
Member,guild.id?
permissions , not permission
Hunter pointed that out
@slate swan 
Requires a role object.
Lol
triggered I got no self control lol
get_role(role_id, /)```
Returns a role with the given ID.
The longest break i took from discord was for 13 hrs
I assume the get is the utils function pretty bad naming
The longest break I took was, uhh, 3-4 days Or smth
Yes it is
1 day the past 3 weeks
Lol
Been awhile since I really didn't do anything a whole day
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
what was the profile class for?
For badges and stuff
looking at the error, permissions_for needs a member object
Nitro badge, booster and stuff
alright, wanna know what's off?
oh
the problem is this:
permissions_for accepts a Role or Member object on v2+ (https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.permissions_for)
but it doesn't on v1.7.3 (https://discordpy.readthedocs.io/en/v1.7.3/api.html#discord.abc.GuildChannel.permissions_for)
conclusion: you can update if you want to BUT you'll have to take a look at breaking changes
what sniper said
you're on v1.7.3 mate
the docs you're looking at are master (v2+)
well, now you don't anymore apparently
you can verify this by
print(discord.__version__)
make sure to read the breaking changes
there must be
I guess you could just use role.permissions
not sure if it's can be changed per channel... I don't do moderation bots
probably isn't
You can
afaik yes
does anyone have a sample piece of code where their bot sends a confirmation message and awaits for a reaction to continue the function, could obv work it out myself if no one has one on hand theyre willing to share
but figured someone would have something similar available here
docs do
oh cool, any idea what its listed under
bruh
wait_for,, ill find it
ty
i can look it up but appreciate trying to wrangle Python to help
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
finally
Ye commands
haha nice job
I am typing on my phone ;-;
this has the example
yep it does, thanks
RIP
I highly recommend using the search function on the docs it saves a lot of time asking this question here.
would have searched wait_for like i said if i knew an example was listed there
Basically all those things which u can see on a user profile
so they got renamed to flags?
Yea, for whatever reason
PublicFlags iirc
!d discord.UserFlags
class discord.UserFlags```
Represents Discord User flags.
Yea
hm
You could also save aliases of them if they change their name
Ngl, I liked the discord.Profile implement
how do you get a discord bot to create an invite and print it in the termanal
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
hmmmm i'll have to try it
@commands.has_permissions(ban_members=True)
@client.slash_command(description="Unbans a user")
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
embed=disnake.Embed(color=0x00d60e, title=f"Successfully unbanned {user}", description=f"Unbanned {user} by {ctx.author.mention}")
await ctx.send(embed=embed)
return
how to make this so that if they entered a wrong username and tag it will send that it is wrong
error says it all?
U can't have two cogs with the same name
Then u r trying to reload a cog that's already loaded
Idk
Yea
The file named maincogs is causing the error
Ah I see the error
discord_slash is causing it most probably
Ah
told u, no two cogs with the same name
(:
BTW a fork like disnake or pycord or smth would be preferred instead of dpy 2.0
as a disnake user, its good
disnake has timeouts 😍
uh
this thing
yeah but i dont think it was "new" but sure you can call it new
disnake is a really good fork, d.py is not maintained anymore so more API's are updated more it will became useless
how would you make a create invite and send it to your dms?
no, but don't do import disnake as discord just search replace it
just tell us if you get any errors whilst switching
Yea... They gonna get updated with new features
np
how did you create the 9 months ago in your about me?
uh read discord message formatting guide
Yea
how would you make a create invite and send it to your dms?
It has everything discord.py has, and more
disnake has built in slash commands, you don't need the package to work with disnake (as tvrsier said)
you can put a backslash before an emoji (on discord) and get the unicode
or copy it from google
oh cool thanks
Yes
yeh oops
?
I thought you were talking about that only
could anyone help me with making a warn command?
https://paste.pythondiscord.com/umapuqonar.py
not necesarry
thanks
i dont even know what the "u" does
oh i think its for unicodes idk
now tap enter and copy the thing that the message changes to
I know lol, I was showing them
uh not too sure, I haven't worked with slash commands much
okay then
so I am in a server on another account with my bot in it i want it to create an invite into the server and send it to me is that possible
i can't run a command from it
create an invite to invite the bot or to join the server
that is the easy way i want to do it with my bot
i know i am asking u do u want ur bot to send u an invite to invite the bot or to join the server
thats the whole point of this channel.
discord bots
join the server
that my bot is in
yeah i dont think its possible either way unless you and youre bot are in a mutual server
we are
!d discord.abc.GuildChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
the account youre in now
yes
well what do u have in your code now?
umm let me get it
the dm one gives you an invite from where you sent the command
the paste it
i know
so if u want ur bot to dm u a server invite its like this
@bot.command()
async def dm (ctx,member : discord.Member):
await member.send('put in the server invite here')```
i think, not 100%
the way u use it is "{prefix}dm {user}"
right
how would you do that i am not very in depth but i know the basics of it
does it work
ctx and inter are different things..?
yes, it works, use it
@bot.slash_command()
async def hello(inter):
""" Responds with 'World' """
await inter.send("World")
``` shortest way, docstring will still apply as description.
inter is for slash commands, ctx is not
i don't have a invite to give it that the prob
@cedar smelt the name can by anything, what matters is the class instance it's from
get the invite from ur other account
You are using Disnake?
!voice verify
Voice verification
Can’t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
Then both methods work
use that in #bot-commands
i did
why are u using it in discord bots?
i dont know
this channel is for bots right?
dont use it here 😐
ok
ok
can anyone please help me figure out how to have main.py run the bot and have my commands written and "stored" in Commands.py?
not the point why i replied to #!/usr/bin/python3 is because he said what i was looking for i jjust dont know how to build it.
ok look do u have access to ur other account?
no because it is protected by 2fa and i don't have that for another 8 hours
if u want to generate an invite link do
@bot.command()
async def invite (ctx,member : discord.Member):
invite = await ctx.channel.create_invite()
await member.send(invite)```
.
await member.send dms the user an invite link
can someone help me
cogs
wat
with?
cogs?
yeah
what are cogs
it's payload.message**_**id
oh thank u
could anyone help me with making a warn command?
https://paste.pythondiscord.com/umapuqonar.py
:^(
how do i start it
wdym-
fvindi can u help me what does it mean by list index out of range
lets say list have 2 items and you try to get the 3rd one that does not exists
not that great with errors, nor have i got it before
your list dosnt work cause of +1
just copy and paste this
@bot.command()
async def invite (ctx,member : discord.Member):
invite = await ctx.channel.create_invite()
await member.send(invite)```
no, its because of the indexing
then what do i do to replace that
do i do &createinvites or wut
its like list = [1, 2] print(list[3])
what would i do?
whats ur prefix
do i delete the +1
print the list and see what it gives
ye
&
yes do that
just the prefix? or a thing behind it
i cant print it if i dont call it and when i call it i get this error
omg
what do i change that to or do i remove it
do u know how to use commands and prefixs?
well 0 is minimal
Traceback (most recent call last):
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\notvi\OneDrive\Desktop\Ace Tickets\main.py", line 44, in on_raw_reaction_add
ticket_num = 1 if len(category.channels) == 0 else int(category.channels[-1].name.split('-')[1]) + 1
IndexError: list index out of range```
lemme try
example_list = ["foo","bar","foobar"]
print(example_list[3]) # trying to get 4th item from list, but that does not exists, so it raises error
``` also you are trying to get negative item from list for what I can see
let me guess your problem
category.channels[-1].name doesn't contain a '-'
result => split 1 is out of range
yea i have my whole bot made of them
so instead of listing 3 list 2
0 = first item from list
bro when u asked me i said yes, so use &createinvites use ur knowledge
so how would i call less
call less..?
0 is first object
do i do print([0])
category.channel[0] will select first channel
ye
problem is, the channels have a stinky order
better would be to get a channel via discord utils based on name
u can try print category.channels[0].name
lemme try
Why?
that didn't work would you like a go at it? https://goor.me/iWqBj that is the ide i am using rn
lemme try
launch time?
does not exist?
im not doing stuff for u, ive already given a code and u chose to do the other person's code so dont ask me
COG's don't work
I put your code in
yeah and then what happened
did it say and error?
in the console
can you print category.channels
@steel slatecodes pretty self-described too but i guess he lacking basic knowledge
literally
i know that here is the thing i use these not the other way around
async def Help(ctx):
embed=discord.Embed(title='Help Page!', description=f"%Ping (To tell you if I am online or not) \n %Purge (To purge mass messages) \n %Invite (Opens the invite page to invite me!) \n %Help (To open this page to tell you what commands I have)", color=0x206694)
await ctx.channel.send(embed=embed)
@bot.command()
async def serverinvite (ctx,member : discord.Member):
invite = await ctx.channel.create_invite()
await member.send(invite)```
@commands.has_permissions(kick_members=True)
@client.slash_command(description="Mutes a user")
async def mute(ctx, member: disnake.Member=None, *, reason="The reason was not entered"):
guild = ctx.guild
muted = disnake.utils.get(guild.roles, name="Muted")
if not muted:
muted = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(muted, speak=False, send_messages=False)
await member.add_roles(muted, reason=reason)
await member.send(f"You have been muted in {member.guild.name} for **{reason}** by {ctx.author.mention}")
embed=disnake.Embed(color=0x00d60e, title=f"Successfully muted {member.mention}", description=f"Muted {member.mention} for {reason}")
await ctx.send(embed=embed)
why does this no work
i never use the bottem one so that why i ask multiple times
you can create a role and give the ROLE permissions yk, instead of every channel lol
this will not invite u from all servers its in tho, only from the servers channel you typing this command in, aka wont work throu dm with bot
right hmm
!d disnake.Member.timeout ?
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
is this for a cog or does it work normally aswell not in a cog
that should work in main
so i use client or bot do i replace commands with that or just copy and pasta
@echo wasp idk what he wrote 
sure but how do i print without calling the command
you should edit it to bot.command if thats what u have
That code is meant for cog so self should be passed first.
@cloud dawnit was but i assume he dont use cogs why i removed all self
so he has to change decoration
i do not good guess but i know what they are
error:
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: choice() takes 2 positional arguments but 3 were given
code:
@bot.command()
@commands.has_permissions(administrator=True)
async def invites (ctx):
em1=discord.Embed(description="invite link", colour=0x1f8b4c)
em2=discord.Embed(description="invite link", colour=0x1f8b4c)
await ctx.send(random.choice(em1, em2))```
@echo waspshow the codes u have rn
you need to give it a list
the indentation is pretty screwed tho what i can see
here
because of reasons
ok
I use cleitn events
where can i learn python to start making a discord bot? i want a good source to learn pls
@steel slatefix all ur codes, it all functions has diffrent indentations
nice goormide using the same
ok give me 5 minutes
?
uh anyone?
that is vscode my bad
bot also has events, you can just use bot instead of client and bot but whatever
ye its vscode can u help me on it
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
they are all paid lmfao
too much copy pasta
mhm
iirc they're not?
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
Yeah they aren't
lol it is how i found in docs lol
i follow close
i fixed it all now
not really
cant belive u dont get indentation errors
its still diffrent in all functions
sum has 2 space some has too many tabs
well it is a poopy ide so i usally use vscode but i am on chromebook rn so limited recources
In that case I'd suggest online vsc
gitpod
ok
explains why chromebooks so cheap, pure crap 😄
lol
ok i got it moved
now wut
ok so i ran this on my bot it worked in dm n dm:ed back invites from server
but this is inside a cog
how do you make a cog i haven't experimented with them very much
I'm sorry but this doesn't really seem appropriate.
@cloud dawnwhat u mean?
you build it them if it is not right
That this is not really appropriate code to place here.
why not ?
wdym it is discord-bots
he wants bot to give him invites to servers his bot are in
This raises a lot of privacy concerns for me.
rn i know everyone that the bot is in a server with
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
@cloud dawnnot for me i had a reason make it cause i did a server throu bot and needed bot to give invites to my discord account to access bots created server
nothing sketchy
and i dont selfbot so
Let's halt this for now then, if you think i'm mistaken please contact @novel apex
hmmm let me think
await self.bot.create_guild() how else u join ur servers
ofc u need bot to send u invites
right i think i'll be talking to a modmail
Still doesn't make it appropriate to create invite for every guild your bot is in.
it is in 8 and i own half
its only in 1 guild, but i get it its bad code for a selfbotter
There was a whole discussion on this yesterday as well.
selfbot or not, still raises concerns for me.
nice
ok mods can delete code if they not like it
Here is the discussion if interested -> https://discordapp.com/channels/267624335836053506/343944376055103488/932764478272061452
ok with that i want to know my bot is etup for small not large and it does this every boot up ```@bot.event
async def on_ready():
for guild in client.guilds:
print(guild.name)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')``` it is a thing to make sure the bot sees them all so i don't get it
@cloud dawnoh well i see what u mean if lets say u have a public bot that peoples are using in their servers
for me its only 1 guild and my bot is private
but ofc i cant know what others bot are
We don't know if that is the case, i understand if it is only in some private guilds or only my friends use it etc. But i've seen enough cases that people abused code highly in terms of self botting.
mine is small aswell and usally in heroku so i never get the guilds
@cloud dawnight i remove code then so no kids abuse it
@echo wasp Sorry for the intrusion, thanks for understanding and being patient about contacting modmail
can we continue in dms so it is closed 1 and 1 so no one can just grab the code?
np i haven't quite yet i'm still stiring on it
u have the code already lol
what about issues?
Could you DM the code? I will ask modmail about this and when responded i will ping the usual helpers here in i private guild so we all know about it.
Some of the others also had some issues with this in the past.
I do now and then it is just some of these i don't get
Print it before the error
sorry im just going to sleep can we do this tmr?
ill dm u tmr
ye
I'm pinging a member. But I get this error
Sure you can, but I don't promise anything
ye ik
Gn
byeee
thats weird
@heavy radishoh u use member, but u named parameter user
Yea, I just figured
😄
sometimes u get blind for a second
Lmao
well time for me to grab ☕ and wakeup
code: ```py
@bot.command(aliases=['ub'])
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
em1=discord.Embed(desciption=f"{member.mention} has been unbanned")
em2=discord.Embed(desciption=f"{member.mention}, you have been unbanned")
await ctx.guild.unban(user)
await ctx.send(embed=em1)
await member.send(embed=em2)
return```error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'mention'```
member is just string, you can't mention it in this case
pretty selfexplained error
should i change it to user?
Also the .send might cause error because the member was banned
!e ```py
print("hello".mention)
@cloud dawn :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'str' object has no attribute 'mention'
no better make a typehint for member object
member: discord.Member
But that user would be in guild?
u can post the discordID i think
Wouldn't the typehint be discord.User instead
no, ive done it before on the ban/kick command so they're right 🙂
But in those cases the user is in guild, both should work tho
@tawdry perchwell u can keep it as a string if u want - but then you need to fetch that member object
But that member is not in guild?
user = await self.bot.fetch_user(user_discord_id)
and have discord id as parameter?
await ctx.guild.unban(user)
discord.ext.commands.errors.MemberNotFound: Member "fvndi#7450" not found.```
got another error
😭
🧠
@commands.command(aliases=["ub"])
@commands.has_permissions(ban_members=True)
async def unban(self, ctx, member:discord.User, *, reason="No reason provided"):
user = await self.bot.fetch_user(member.id)
try:
await user.send(f"You have been **un-banned** from the {ctx.guild.name}\nreason: {reason}")
except:
pass
await ctx.send(f"{user.mention} **has been un-banned.**\n*reason: {reason}*")
await ctx.guild.unban(user, reason=reason)
``` here is my old unban code
damn, that's useless

also sending that the user has been unbanned before he's actually unbanned is quite funny
i said its old n i dont use it 😄
Bare except, key: value pep8 violation, reason isn't type hinted, cache isn't use -> instant fetch
do you really need to typehint every single parameter tho? seems obvious sometimes, I'd only want a typehint if it needs to be converted
member:discord.User calling member a user, then re-fetching the user ;-;
Well yeah if everyone would typehint it would make reading code so much easier.
Pandabweer be like I'm about to end this man's whole career
In docs and for debugging other's code, I'd agree
yes very shitty code 🥲
nah, you were already using cogs at that time, can't complain
How long have you guys been coding for?
just on n off sometimes
1year
I want the bot to send a message for every new member, but it doesn't work. ``` import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f'Hello {member.name}, welcome to my Discord server!'
)
client.run(TOKEN)```
The second part of the code doesn't work
@commands.Cog.listener()
async def on_message(self, message):
Unlock = discord.PermissionOverwrite(send_messages=True)
Lock = discord.PermissionOverwrite(send_messages=False)
Role = message.guild.default_role
if message.channel.id == 814207750342705164 and message.content.lower().startswith("rpg miniboss"):
await message.channel.set_permissions(Role, overwrite=Unlock)
await message.channel.send(f":white_check_mark: Unlocked {message.channel.name}")
await asyncio.sleep(10.0)
if Role == Unlock:
await message.channel.set_permissions(Role, overwrite=Lock)
await message.channel.send(f":white_check_mark: Locked Down {message.channel.name}")
``` After if role == unlock
error?
none
shouldt await member.send("hi") be enough?
This looks like old code (sorry)
You don't need to create a dm before dm'ing anymore.
What you are doing right now is sending a message to a channel type.
Any idea why?
does anyone know how to hide cogs from custom help commands?
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_member_join(member):
await member.send(
f'Hello {member.name}, welcome to my Discord server!'
)
client.run(TOKEN)
``` Try this :)
hidden=True
do i put that at the start?
Thank you
What do you mean by old code?
await member.create_dm()
``` This used to be the way to do it but not anymore.
doesn't have intents
Like 3 years ago
U will go mad with Vanilla JS, since there's no type checking in it
@honest vessel can you dm me the cog version please for secutry reasons as why we had to halt
No work
Also
@cloud dawn oh k
you mean converters? since python doesn't really either 🤔
No, just a general type checking and type hinting is what am talking about
where would i put that in my code? just after the class?
everything is datatype any, I'd say?
use ext.commands for commands and how can a discord.Role object be equal to a discord.PermissionOverwrite object?
doesn't make sense
Yes, iirc
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_member_join(member):
await member.send(
f'Hello {member.name}, welcome to my Discord server!'
)
client.run(TOKEN)
!d typing.Any
typing.Any```
Special type indicating an unconstrained type.
• Every type is compatible with [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any").
• [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") is compatible with every type.
all? please no
Imagine type hinting to Any
I see it in docs all the time
I always use all
gl on that :))
@cloud dawn is still doesn't work
If you then "release" your bot you turn off intents and debug your bot for the last time.
any errors?
you forgot to tell him he has to enable it in discord portal too
Have you enabled intents?
^
No
Yes
in portal
Could you provide the current code you got?
The one you sent me
The first or the last one?
First
please don't blindly follow YT tutorials
@lyric flint Try this.
And regen your token
So you sended code that isn't yours?
i am following someone on how to make a cog
never made one before
Try 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.
ok i used this https://youtu.be/vQw8cFfZPx0
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:...
yuck
❤️
You also need to check the date of videos when coding 9 May 2019
import discord
from discord.ext import commands
class Mycog(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Mycog(bot))
``` minimal cog
Even for 2019 that is not really good code.
cmon
people with no previous experience have no idea what this is
lol that is what he wrote down for me to follow
@cloud dawn now im getting this error: discord.errors.PrivilegedIntentsRequired
from discord.ext.commands import Cog, Bot
class Mycog(Cog):
def __init__(self, bot: Bot):
self.bot = bot
def setup(bot: Bot):
bot.add_cog(Mycog(bot))
!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.
perfectionist 😄
sorry :3
Now it is perfect
typehintPanda
useless import
We're getting there
Where?
nvm, typehinting bot even? lol
can be a discord.Client too tho, not per se, but yeah
typehint-fascist
Can also be disnake.ext.commands.AutoShardedBot
Or disnake.ext.commands.AutoShardedInteractionBot
Or disnake.AutoShardedClient
that's what I'm saying abt the typehint stuff
"obvious shit" doesn't need to be imo
like I won't pass a string if it says bot or client lol
Typehinting is for your comfort, if you typehint, your IDE/code editor will show you autocomplete suggestions based on type of an object
Union[disnake.ui.ActionRow, disnake.ui.Item, List[Union[disnake.ui.ActionRow, disnake.ui.Item, List[disnake.ui.Item]]]]) Disnake typehint for objects
art
@cloud dawn It's working, thanx for your help 🙂
😉
Sadru is a typing master
Behold 
description=""
Your option would look to something like that
Option(
name="opt1",
description="Description here",
...
)
You need to provide the option in the decorator for the description.
hmm well, bot doesn't do its job
cogs/slash/owner-slash.py lines 50 to 57
options=[
Option(
name="message",
description="The message you want me to repeat.",
type=OptionType.string,
required=True
)
],```
Here is an example for an option.
How do I change data in an SQLite3 database with a discord command
/leaderboard update header: points update to: 1
Is what I want to do
I have the actual command, but it doesn't interact with the db
what app is that you use to view this? (sorry non relevant to your question)
I use sqlite db browser
Check it out
could you give the link?
thank you 😄
That's is not it
oh
np, thx!
Help?
To start with it, you should start by making connection to that db
then: parse the arguments (eg) ```py
@commands.command()
async def update_db(self, ctx, amount: int):
async with aiosqlite.connect("db/path/here") as db:
await db.execute()
then do sql statements inside execute
You can just create a bot var so you don't have to open it all the time
Ye, but that was just example. I made the mistake and didn't use botvar 😔
Heyy, WiFi died. WDYM? I don't have any role other than default roel
@commands.Cog.listener()
async def on_message(self, message):
Unlock = discord.PermissionOverwrite(send_messages=True)
Lock = discord.PermissionOverwrite(send_messages=False)
Role = message.guild.default_role
if message.channel.id == 814207750342705164 and message.content.lower().startswith("rpg miniboss"):
await message.channel.set_permissions(Role, overwrite=Unlock)
await message.channel.send(f":white_check_mark: Unlocked {message.channel.name}")
await asyncio.sleep(10.0)
if Role == Unlock:
await message.channel.set_permissions(Role, overwrite=Lock)
await message.channel.send(f":white_check_mark: Locked Down {message.channel.name}")
``` The second part of the code doesn't work (after if role == unlock:)
Termux (I'm on mobile)
oh
heyy, can u help?
are you comparing role obj to discord.PermissionsOverwrite?
yes
that should never be True
I'm trying to overwrite a role
discord.Role is not same as discord.PermissionsOverwrite
ok
You can take a look at this issue I've been involved in yesterday
https://github.com/kkrypt0nn/Python-Discord-Bot-Template/issues/51#issuecomment-1015315277
There is an example on how to make one.
How do I fix it?
you are comparing 2 different objects to see if they are equal to, which they never be
Ahhhhh
yeah
How do I fix it? Is there a discord.permission way
thats the role I was talking about
i understand now
what exactly are you trying to do?
Well
I mean in if statement
any help?
When someone does a command (for another bot) which starts with RPG miniboss, i'm opening the channel, after 1min, i'm closing it. Some times, people manually close the channel, for that instance, i'm using the if statement to check if its open, and if it is, close it
and when you check if role == discord.PermissionsOverwrites. Are you trying to check if role has specific permission?
yes
there should be method for it
Hmmm
!d discord.Role | just for me to read the docs
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
!d discord.Role.permissions perhaps this could work
property permissions: discord.permissions.Permissions```
Returns the role’s permissions.
Is this for me?
Exactly
ye
How will i use it?
Role = discord.permissions.Permissions
no I mean, use that to get role permissions and then see if role has some specific perms
Umm
sorry, I can't really explain it
can someone help me with a cooldown on a command?
@commands.command()
@commands.cooldown(1,20, commands.user)
async def beg(self, ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
earnings = random.randrange(1000)
mbed = nextcord.Embed(title="**BEGGING?**", description=f"Someone gave you ${earnings}. Hope your grateful")
mbed.set_footer(text="My child was begging, hope it was worth it")
await ctx.send(embed=mbed)
users[str(user.id)]["wallet"] += earnings
with open("bank.json", 'w') as f:
json.dump(users,f)
yea, i think i figured it
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
Thank you
Hi guys, which one is prohibit send api?
Hmm?
for user
the timeout user
You want to know how to time someone out?
yes
What lib are you using?
The timeout feature is not support on discord.py irrc
U gotta change the internals
Nope
how?
So you either need to use a fork or fuck with the internals
If you decide to go down the fork route I would suggest disnake
!pypi disnake
Send the code so he can copy and paste
let me think..
looks like you’re trying to find the size of an avatar when it’s type string
ik i fixed it
good
Nah, am cool lol
Do I need to do any imports or any pip package installs?
It does
@tawdry perch can I have two tables in one database file?
Sure, multiple ones
Ok
how can i have per server settings? (i wanna link a channel to the bot)
I am trying to make a sell command, and I want to make it such that, the user can input the item name (with spaces), along with the quantity in the same line. How do I go about separating both?
how do i get a channel by its id?
wdym
i mean message sorry
like ctx.guild.get_message(id)
what will this return?
what do you want it to return?
An int value of the channel id.
well, i wanted a message not channel
You mean the actual message object?
yes
Oh
u wanna get message id?
You can just do ctx.message
well, i dont want to get the ctx message
it returns the message object of the message which has the command
i want to get a specific message with its ID
using it's ID?
yes
ahh
idk lol
can someone help me here?
thx!
you can use bot.wait_for for that
you just need to use two different keyword arguments for that
async def(ctx, item, price):```
if the items names have spaces in them, that's a little bit more trouble
he told us that the price and item strings will be a few words conceted with spaces
because the way discord.py and it's forks parse arguments it will consider the second part of the name as the price
Nah, I wanna do it single line
Thing is,
in that case you could just invert the order and have no more issues
I implied that the item name would have a space in it
async def sell(ctx, price, *, item)```
as long as you indicate price first, everything else will be considered the item
What does the * do?
With a currency bot when i have a nickname it changes the id of the user to someone else is their a way to fix this at all?
it makes discord.py consider the rest of the string as the item
Oh ok
Oh and
One more question
How can I detect if the user has skipped giving the price value?
well because of the way the example i showed you is defined
if the price or the item name is missing
it will throw an error called MissingRequiredArgument
Ah
do you know what an error handler is?
Yep
and do you have one?
I just do commands.MissingRequiredArgument?
ye I do
yeah just make a case for that then
Okeh
commands.MissingRequiredArgument yes
thanks
you're welcome
So i was makng a command that replies 'wassup' when someone sends a message and it contains hi or hello, but it is not working!
Code:
greet_inputs = ['hello', 'hi', 'wassup']
@bot.event
async def on_meassage(msg):
if mgs.user == bot.user:
return
for greets in greet_inputs:
if greets in str(msg.content).lower():
await msg.channel.send(f'wassup {str(msg.author)[:-5]}!')
break
await bot.process_commands(msg)
Output:
No errors. Just not working even if the message contains hi or hello
greets is not defined
Why iterate?
just
...```
Like this?
if message.content in greet_inputs:
await msg.channel.send(f'wassup {str(msg.author)[:-5]}!')
I got no self control lol